24 #include <sys/param.h> 26 #ifdef FLOW123D_HAVE_PYTHON 28 #endif // FLOW123D_HAVE_PYTHON 34 #include <boost/format.hpp> 35 #include <boost/unordered_map.hpp> 100 #ifdef FLOW123D_DEBUG_PROFILER 105 const int timer_no_child=-1;
107 Timer::Timer(
const CodePoint &cp,
int parent)
113 full_hash_(cp.hash_),
114 hash_idx_(cp.hash_idx_),
115 parent_timer(parent),
117 total_deallocated_(0),
119 current_allocated_(0),
122 #ifdef FLOW123D_HAVE_PETSC 123 , petsc_start_memory(0),
124 petsc_end_memory (0),
125 petsc_memory_difference(0),
126 petsc_peak_memory(0),
127 petsc_local_peak_memory(0)
128 #endif // FLOW123D_HAVE_PETSC 130 for(
unsigned int i=0; i< max_n_childs ;i++) child_timers[i]=timer_no_child;
138 os <<
" Timer: " << timer.tag() << endl;
139 os <<
" malloc: " << timer.total_allocated_ << endl;
140 os <<
" dalloc: " << timer.total_deallocated_ << endl;
141 #ifdef FLOW123D_HAVE_PETSC 142 os <<
" start: " << timer.petsc_start_memory << endl;
143 os <<
" stop : " << timer.petsc_end_memory << endl;
144 os <<
" diff : " << timer.petsc_memory_difference <<
" (" << timer.petsc_end_memory - timer.petsc_start_memory <<
")" << endl;
145 os <<
" peak : " << timer.petsc_peak_memory <<
" (" << timer.petsc_local_peak_memory <<
")" << endl;
146 #endif // FLOW123D_HAVE_PETSC 152 double Timer::cumulative_time()
const {
156 void Profiler::accept_from_child(
Timer &parent,
Timer &child) {
158 for (
unsigned int i = 0; i < Timer::max_n_childs; i++) {
159 child_timer = child.child_timers[i];
160 if (child_timer != timer_no_child) {
162 accept_from_child(child, timers_[child_timer]);
166 parent.total_allocated_ += child.total_allocated_;
167 parent.total_deallocated_ += child.total_deallocated_;
168 parent.alloc_called += child.alloc_called;
169 parent.dealloc_called += child.dealloc_called;
171 #ifdef FLOW123D_HAVE_PETSC 172 if (petsc_monitor_memory) {
174 parent.petsc_memory_difference += child.petsc_memory_difference;
175 parent.current_allocated_ += child.current_allocated_;
179 parent.petsc_peak_memory =
max(parent.petsc_peak_memory, child.petsc_peak_memory);
181 #endif // FLOW123D_HAVE_PETSC 183 parent.max_allocated_ =
max(parent.max_allocated_, child.max_allocated_);
187 void Timer::pause() {
188 #ifdef FLOW123D_HAVE_PETSC 189 if (Profiler::get_petsc_memory_monitoring()) {
191 PetscMemoryGetMaximumUsage(&petsc_local_peak_memory);
192 if (petsc_peak_memory < petsc_local_peak_memory)
193 petsc_peak_memory = petsc_local_peak_memory;
195 #endif // FLOW123D_HAVE_PETSC 198 void Timer::resume() {
199 #ifdef FLOW123D_HAVE_PETSC 200 if (Profiler::get_petsc_memory_monitoring()) {
203 PetscMemorySetGetMaximumUsage();
205 #endif // FLOW123D_HAVE_PETSC 209 #ifdef FLOW123D_HAVE_PETSC 210 if (Profiler::get_petsc_memory_monitoring()) {
213 PetscMemorySetGetMaximumUsage();
214 PetscMemoryGetCurrentUsage (&petsc_start_memory);
216 #endif // FLOW123D_HAVE_PETSC 218 if (start_count == 0) {
228 #ifdef FLOW123D_HAVE_PETSC 229 if (Profiler::get_petsc_memory_monitoring()) {
231 PetscMemoryGetCurrentUsage (&petsc_end_memory);
232 petsc_memory_difference += petsc_end_memory - petsc_start_memory;
235 PetscMemoryGetMaximumUsage(&petsc_local_peak_memory);
236 if (petsc_peak_memory < petsc_local_peak_memory)
237 petsc_peak_memory = petsc_local_peak_memory;
239 #endif // FLOW123D_HAVE_PETSC 241 if (forced) start_count=1;
243 if (start_count == 1) {
244 cumul_time += (
TimePoint() - start_time);
255 void Timer::add_child(
int child_index,
const Timer &child)
257 unsigned int idx = child.hash_idx_;
258 if (child_timers[idx] != timer_no_child) {
262 i=( i < max_n_childs ? i+1 : 0);
263 }
while (i!=idx && child_timers[i] != timer_no_child);
264 ASSERT(i!=idx)(tag()).error(
"Too many children of the timer");
268 child_timers[idx] = child_index;
273 string Timer::code_point_str()
const {
274 return boost::str(
boost::format(
"%s:%d, %s()") % code_point_->file_ % code_point_->line_ % code_point_->func_ );
284 if (_instance == NULL) {
285 MemoryAlloc::malloc_map().reserve(Profiler::malloc_map_reserve);
292 static CONSTEXPR_ CodePoint main_cp = CODE_POINT(
"Whole Program");
294 const long Profiler::malloc_map_reserve = 100 * 1000;
295 CodePoint Profiler::null_code_point = CodePoint(
"__no_tag__",
"__no_file__",
"__no_func__", 0);
299 set_memory_monitoring(
true,
true);
306 start_time( time(NULL) ),
310 #ifdef FLOW123D_DEBUG_PROFILER 311 timers_.push_back(
Timer(main_cp, 0) );
318 void Profiler::propagate_timers() {
319 for (
unsigned int i = 0; i < Timer::max_n_childs; i++) {
320 unsigned int child_timer = timers_[0].child_timers[i];
321 if ((
signed int)child_timer != timer_no_child) {
323 accept_from_child(timers_[0], timers_[child_timer]);
331 task_description_ = description;
338 flow_name_ = program_name;
339 flow_version_ = program_version;
340 flow_branch_ = branch;
341 flow_revision_ = revision;
347 int Profiler::start_timer(
const CodePoint &cp) {
348 unsigned int parent_node = actual_node;
350 int child_idx = find_child(cp);
354 child_idx=timers_.size();
355 timers_.push_back(
Timer(cp, actual_node) );
356 timers_[actual_node].add_child(child_idx , timers_.back() );
358 actual_node=child_idx;
361 timers_[parent_node].pause();
363 timers_[actual_node].start();
370 int Profiler::find_child(
const CodePoint &cp) {
371 Timer &timer =timers_[actual_node];
372 unsigned int idx = cp.hash_idx_;
373 unsigned int child_idx;
375 if (timer.child_timers[idx] == timer_no_child)
break;
377 child_idx=timer.child_timers[idx];
378 ASSERT_LT(child_idx, timers_.size()).error();
379 if (timers_[child_idx].full_hash_ == cp.hash_)
return child_idx;
380 idx = ( (
unsigned int)(idx)==(Timer::max_n_childs - 1) ? 0 : idx+1 );
381 }
while ( (
unsigned int)(idx) != cp.hash_idx_ );
387 void Profiler::stop_timer(
const CodePoint &cp) {
388 #ifdef FLOW123D_DEBUG 390 Timer &timer=timers_[actual_node];
391 for(
unsigned int i=0; i < Timer::max_n_childs; i++)
392 if (timer.child_timers[i] != timer_no_child)
393 ASSERT(! timers_[timer.child_timers[i]].running())(timers_[timer.child_timers[i]].tag())(timer.tag())
394 .error(
"Child timer running while closing timer.");
396 unsigned int child_timer = actual_node;
397 if ( cp.hash_ != timers_[actual_node].full_hash_) {
399 for(
unsigned int node=actual_node; node != 0; node=timers_[node].parent_timer) {
400 if ( cp.hash_ == timers_[node].full_hash_) {
402 for(; (
unsigned int)(actual_node) != node; actual_node=timers_[actual_node].parent_timer) {
403 WarningOut() <<
"Timer to close '" << cp.tag_ <<
"' do not match actual timer '" 404 << timers_[actual_node].tag() <<
"'. Force closing actual." << std::endl;
405 timers_[actual_node].stop(
true);
408 timers_[actual_node].stop(
false);
409 actual_node = timers_[actual_node].parent_timer;
412 if (actual_node == child_timer)
416 timers_[actual_node].resume();
424 timers_[actual_node].stop(
false);
425 actual_node = timers_[actual_node].parent_timer;
428 if (actual_node == child_timer)
432 timers_[actual_node].resume();
437 void Profiler::stop_timer(
int timer_index) {
441 if (timers_[timer_index].running()) {
442 ASSERT_EQ(timer_index, (
int)actual_node).error();
443 stop_timer(*timers_[timer_index].code_point_);
450 void Profiler::add_calls(
unsigned int n_calls) {
451 timers_[actual_node].call_count += n_calls-1;
457 if (!global_monitor_memory)
460 MemoryAlloc::malloc_map()[p] =
static_cast<int>(size);
461 timers_[actual_node].total_allocated_ += size;
462 timers_[actual_node].current_allocated_ += size;
463 timers_[actual_node].alloc_called++;
465 if (timers_[actual_node].current_allocated_ > timers_[actual_node].max_allocated_)
466 timers_[actual_node].max_allocated_ = timers_[actual_node].current_allocated_;
472 if (!global_monitor_memory)
475 int size =
sizeof(p);
476 if (MemoryAlloc::malloc_map()[(long)p] > 0) {
477 size = MemoryAlloc::malloc_map()[(long)p];
478 MemoryAlloc::malloc_map().erase((
long)p);
480 timers_[actual_node].total_deallocated_ += size;
481 timers_[actual_node].current_allocated_ -= size;
482 timers_[actual_node].dealloc_called++;
487 const int measurements = 100;
491 for (
unsigned int i = 1; i < measurements; i++) {
496 while ((t2 - t1) == 0) t2 =
TimePoint ();
502 return (result / measurements) * 1000;
506 std::string common_prefix( std::string a, std::string b ) {
507 if( a.size() > b.size() )
std::swap(a,b) ;
508 return std::string( a.begin(), std::mismatch( a.begin(), a.end(), b.begin() ).first ) ;
513 template<
typename ReduceFunctor>
514 void Profiler::add_timer_info(ReduceFunctor reduce,
nlohmann::json* holder,
int timer_idx,
double parent_time) {
517 Timer &timer = timers_[timer_idx];
518 ASSERT(timer_idx >=0)(timer_idx).error(
"Wrong timer index.");
519 ASSERT(timer.parent_timer >=0).error(
"Inconsistent tree.");
522 string filepath = timer.code_point_->file_;
525 #ifdef FLOW123D_SOURCE_DIR 526 string common_path = common_prefix (
string(FLOW123D_SOURCE_DIR), filepath);
527 filepath.erase (0, common_path.size());
534 double cumul_time_sum;
535 node[
"tag"] = timer.tag();
536 node[
"file-path"] = filepath;
537 node[
"file-line"] = timer.code_point_->line_;
538 node[
"function"] = timer.code_point_->func_;
539 cumul_time_sum = reduce(timer, node);
543 if (timer_idx == 0) parent_time = cumul_time_sum;
544 double percent = parent_time > 1.0e-10 ? cumul_time_sum / parent_time * 100.0 : 0.0;
545 node[
"percent"] = percent;
549 bool has_children =
false;
550 for (
unsigned int i = 0; i < Timer::max_n_childs; i++) {
551 if (timer.child_timers[i] != timer_no_child) {
552 add_timer_info (reduce, &children, timer.child_timers[i], cumul_time_sum);
562 node[
"children"] = children;
571 void save_nonmpi_metric (
nlohmann::json &node, T * ptr,
string name) {
572 node[name +
"-min"] = *ptr;
573 node[name +
"-max"] = *ptr;
574 node[name +
"-sum"] = *ptr;
577 std::shared_ptr<std::ostream> Profiler::get_default_output_stream() {
581 return make_shared<ofstream>(json_filepath.c_str());
585 #ifdef FLOW123D_HAVE_MPI 594 int mpi_rank, mpi_size;
601 bool temp_memory_monitoring = global_monitor_memory;
602 set_memory_monitoring(
false, petsc_monitor_memory);
614 int call_count = timer.call_count;
615 double cumul_time = timer.cumulative_time ();
617 long memory_allocated = (long)timer.total_allocated_;
618 long memory_deallocated = (
long)timer.total_deallocated_;
619 long memory_peak = (long)timer.max_allocated_;
621 int alloc_called = timer.alloc_called;
622 int dealloc_called = timer.dealloc_called;
625 save_mpi_metric<double>(node, comm, &cumul_time,
"cumul-time");
626 save_mpi_metric<int>(node, comm, &call_count,
"call-count");
628 save_mpi_metric<long>(node, comm, &memory_allocated,
"memory-alloc");
629 save_mpi_metric<long>(node, comm, &memory_deallocated,
"memory-dealloc");
630 save_mpi_metric<long>(node, comm, &memory_peak,
"memory-peak");
632 save_mpi_metric<int>(node, comm, &alloc_called,
"memory-alloc-called");
633 save_mpi_metric<int>(node, comm, &dealloc_called,
"memory-dealloc-called");
635 #ifdef FLOW123D_HAVE_PETSC 636 long petsc_memory_difference = (long)timer.petsc_memory_difference;
637 long petsc_peak_memory = (
long)timer.petsc_peak_memory;
638 save_mpi_metric<long>(node, comm, &petsc_memory_difference,
"memory-petsc-diff");
639 save_mpi_metric<long>(node, comm, &petsc_peak_memory,
"memory-petsc-peak");
640 #endif // FLOW123D_HAVE_PETSC 645 add_timer_info (reduce, &jsonChildren, 0, 0.0);
646 jsonRoot[
"children"] = jsonChildren;
647 output_header(jsonRoot, mpi_size);
658 const int FLOW123D_JSON_HUMAN_READABLE = 2;
660 os << jsonRoot.
dump(FLOW123D_JSON_HUMAN_READABLE) << endl;
662 }
catch (exception & e) {
664 ss <<
"nlohmann::json::dump error: " << e.what() <<
"\n";
665 THROW( ExcMessage() << EI_Message(ss.str()) );
669 set_memory_monitoring(temp_memory_monitoring, petsc_monitor_memory);
678 if (profiler_path ==
"") {
679 output(comm, *get_default_output_stream());
681 json_filepath = profiler_path;
682 std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
704 const int FLOW123D_MPI_SINGLE_PROCESS = 1;
705 output_header(jsonRoot, FLOW123D_MPI_SINGLE_PROCESS);
712 int call_count = timer.call_count;
713 double cumul_time = timer.cumulative_time ();
715 long memory_allocated = (long)timer.total_allocated_;
716 long memory_deallocated = (
long)timer.total_deallocated_;
717 long memory_peak = (long)timer.max_allocated_;
719 int alloc_called = timer.alloc_called;
720 int dealloc_called = timer.dealloc_called;
722 save_nonmpi_metric<double>(node, &cumul_time,
"cumul-time");
723 save_nonmpi_metric<int>(node, &call_count,
"call-count");
725 save_nonmpi_metric<long>(node, &memory_allocated,
"memory-alloc");
726 save_nonmpi_metric<long>(node, &memory_deallocated,
"memory-dealloc");
727 save_nonmpi_metric<long>(node, &memory_peak,
"memory-peak");
729 save_nonmpi_metric<int>(node, &alloc_called,
"memory-alloc-called");
730 save_nonmpi_metric<int>(node, &dealloc_called,
"memory-dealloc-called");
732 #ifdef FLOW123D_HAVE_PETSC 733 long petsc_memory_difference = (long)timer.petsc_memory_difference;
734 long petsc_peak_memory = (
long)timer.petsc_peak_memory;
735 save_nonmpi_metric<long>(node, &petsc_memory_difference,
"memory-petsc-diff");
736 save_nonmpi_metric<long>(node, &petsc_peak_memory,
"memory-petsc-peak");
737 #endif // FLOW123D_HAVE_PETSC 742 add_timer_info(reduce, &jsonChildren, 0, 0.0);
743 jsonRoot[
"children"] = jsonChildren;
750 const int FLOW123D_JSON_HUMAN_READABLE = 2;
752 os << jsonRoot.
dump(FLOW123D_JSON_HUMAN_READABLE) << endl;
754 }
catch (exception & e) {
756 ss <<
"nlohmann::json::dump error: " << e.what() <<
"\n";
757 THROW( ExcMessage() << EI_Message(ss.str()) );
763 if(profiler_path ==
"") {
764 output(*get_default_output_stream());
766 json_filepath = profiler_path;
767 std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
772 void Profiler::output_header (
nlohmann::json &root,
int mpi_size) {
773 time_t end_time = time(NULL);
775 const char format[] =
"%x %X";
776 char start_time_string[BUFSIZ] = {0};
777 strftime(start_time_string,
sizeof (start_time_string) - 1, format, localtime(&start_time));
779 char end_time_string[BUFSIZ] = {0};
780 strftime(end_time_string,
sizeof (end_time_string) - 1, format, localtime(&end_time));
783 root[
"program-name"] = flow_name_;
784 root[
"program-version"] = flow_version_;
785 root[
"program-branch"] = flow_branch_;
786 root[
"program-revision"] = flow_revision_;
787 root[
"program-build"] = flow_build_;
791 root[
"task-description"] = task_description_;
792 root[
"task-size"] = task_size_;
795 root[
"run-process-count"] = mpi_size;
796 root[
"run-started-at"] = start_time_string;
797 root[
"run-finished-at"] = end_time_string;
800 #ifdef FLOW123D_HAVE_PYTHON 803 if (json_filepath ==
"")
return;
812 #ifndef FLOW123D_HAVE_CYGWIN 814 PyObject * python_module = PythonLoader::load_module_by_name (
"profiler.profiler_formatter_module");
818 PyObject * convert_method = PythonLoader::get_callable (python_module,
"convert" );
820 int argument_index = 0;
821 PyObject * arguments = PyTuple_New (3);
824 PyObject * tmp = PyUnicode_FromString (json_filepath.c_str());
825 PyTuple_SetItem (arguments, argument_index++, tmp);
828 tmp = PyUnicode_FromString ((json_filepath + output_file_suffix).c_str());
829 PyTuple_SetItem (arguments, argument_index++, tmp);
832 tmp = PyUnicode_FromString (formatter.c_str());
833 PyTuple_SetItem (arguments, argument_index++, tmp);
836 PyObject_CallObject (convert_method, arguments);
838 PythonLoader::check_error();
843 MessageOut() <<
"# Note: converting json profiler reports is not" 844 <<
" supported under Windows or Cygwin environment for now.\n" 845 <<
"# You can use python script located in bin/python folder" 846 <<
" in order to convert json report to txt or csv format.\n" 847 <<
"python profiler_formatter_script.py --input \"" << json_filepath
848 <<
"\" --output \"profiler.txt\"" << std::endl;
849 #endif // FLOW123D_HAVE_CYGWIN 855 #endif // FLOW123D_HAVE_PYTHON 860 ASSERT(_instance->actual_node==0)(_instance->timers_[_instance->actual_node].tag())
861 .error(
"Forbidden to uninitialize the Profiler when actual timer is not zero.");
862 _instance->stop_timer(0);
863 set_memory_monitoring(
false,
false);
868 bool Profiler::global_monitor_memory =
false;
869 bool Profiler::petsc_monitor_memory =
true;
870 void Profiler::set_memory_monitoring(
const bool global_monitor,
const bool petsc_monitor) {
871 global_monitor_memory = global_monitor;
872 petsc_monitor_memory = petsc_monitor;
875 bool Profiler::get_global_memory_monitoring() {
876 return global_monitor_memory;
879 bool Profiler::get_petsc_memory_monitoring() {
880 return petsc_monitor_memory;
883 unordered_map_with_alloc & MemoryAlloc::malloc_map() {
884 static unordered_map_with_alloc static_malloc_map;
885 return static_malloc_map;
888 void * Profiler::operator
new (
size_t size) {
889 return malloc (size);
892 void Profiler::operator
delete (
void* p) {
897 void * p = malloc(size);
903 void * p = malloc(size);
908 void *
operator new[] (std::size_t size,
const std::nothrow_t&)
throw() {
909 void * p = malloc(size);
914 void operator delete(
void *p)
throw() {
919 void operator delete[](
void *p)
throw() {
924 #else // def FLOW123D_DEBUG_PROFILER 931 Profiler* Profiler::_instance = NULL;
934 if (_instance == NULL) {
936 set_memory_monitoring(
true,
true);
942 ASSERT(_instance->actual_node==0)(_instance->timers_[_instance->actual_node].tag())
943 .error(
"Forbidden to uninitialize the Profiler when actual timer is not zero.");
944 set_memory_monitoring(
false,
false);
945 _instance->stop_timer(0);
952 #endif // def FLOW123D_DEBUG_PROFILER
static int min(int *val, MPI_Comm comm)
#define OPERATOR_NEW_THROW_EXCEPTION
static int sum(int *val, MPI_Comm comm)
a class to store JSON values
#define MessageOut()
Macro defining 'message' record of log.
double get_resolution() const
std::string format(CStringRef format_str, ArgList args)
void chkerr(unsigned int ierr)
Replacement of new/delete operator in the spirit of xmalloc.
#define ASSERT(expr)
Allow use shorter versions of macro names if these names is not used with external library...
void notify_free(const size_t size)
#define MPI_Reduce(sendbuf, recvbuf, count, datatype, op, root, comm)
static void uninitialize()
static int max(int *val, MPI_Comm comm)
void set_program_info(string program_name, string program_version, string branch, string revision, string build)
void swap(nlohmann::json &j1, nlohmann::json &j2) noexcept(is_nothrow_move_constructible< nlohmann::json >::value andis_nothrow_move_assignable< nlohmann::json >::value)
exchanges the values of two JSON objects
STREAM & operator<<(STREAM &s, UpdateFlags u)
void push_back(basic_json &&val)
add an object to an array
void transform_profiler_data(const string &output_file_suffix, const string &formatter)
Dedicated class for storing path to input and output files.
#define ASSERT_LT(a, b)
Definition of comparative assert macro (Less Than)
string_t dump(const int indent=-1) const
serialization
static Profiler * instance()
#define WarningOut()
Macro defining 'warning' record of log.
static Profiler * _instance
#define MPI_Barrier(comm)
#define THROW(whole_exception_expr)
Wrapper for throw. Saves the throwing point.
void output(MPI_Comm comm, ostream &os)
#define ASSERT_EQ(a, b)
Definition of comparative assert macro (EQual)
void set_task_info(string description, int size)
void notify_malloc(const size_t size)