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_ );
291 const long Profiler::malloc_map_reserve = 100 * 1000;
292 CodePoint Profiler::null_code_point = CodePoint(
"__no_tag__",
"__no_file__",
"__no_func__", 0);
297 start_time( time(NULL) ),
301 static CONSTEXPR_ CodePoint main_cp = CODE_POINT(
"Whole Program");
302 set_memory_monitoring(
true,
true);
303 #ifdef FLOW123D_DEBUG_PROFILER 304 MemoryAlloc::malloc_map().reserve(Profiler::malloc_map_reserve);
305 timers_.push_back(
Timer(main_cp, 0) );
312 void Profiler::propagate_timers() {
313 for (
unsigned int i = 0; i < Timer::max_n_childs; i++) {
314 unsigned int child_timer = timers_[0].child_timers[i];
315 if ((
signed int)child_timer != timer_no_child) {
317 accept_from_child(timers_[0], timers_[child_timer]);
325 task_description_ = description;
332 flow_name_ = program_name;
333 flow_version_ = program_version;
334 flow_branch_ = branch;
335 flow_revision_ = revision;
341 int Profiler::start_timer(
const CodePoint &cp) {
342 unsigned int parent_node = actual_node;
344 int child_idx = find_child(cp);
348 child_idx=timers_.size();
349 timers_.push_back(
Timer(cp, actual_node) );
350 timers_[actual_node].add_child(child_idx , timers_.back() );
352 actual_node=child_idx;
355 timers_[parent_node].pause();
357 timers_[actual_node].start();
364 int Profiler::find_child(
const CodePoint &cp) {
365 Timer &timer =timers_[actual_node];
366 unsigned int idx = cp.hash_idx_;
367 unsigned int child_idx;
369 if (timer.child_timers[idx] == timer_no_child)
break;
371 child_idx=timer.child_timers[idx];
372 ASSERT_LT(child_idx, timers_.size()).error();
373 if (timers_[child_idx].full_hash_ == cp.hash_)
return child_idx;
374 idx = ( (
unsigned int)(idx)==(Timer::max_n_childs - 1) ? 0 : idx+1 );
375 }
while ( (
unsigned int)(idx) != cp.hash_idx_ );
381 void Profiler::stop_timer(
const CodePoint &cp) {
382 #ifdef FLOW123D_DEBUG 384 Timer &timer=timers_[actual_node];
385 for(
unsigned int i=0; i < Timer::max_n_childs; i++)
386 if (timer.child_timers[i] != timer_no_child)
387 ASSERT(! timers_[timer.child_timers[i]].running())(timers_[timer.child_timers[i]].tag())(timer.tag())
388 .error(
"Child timer running while closing timer.");
390 unsigned int child_timer = actual_node;
391 if ( cp.hash_ != timers_[actual_node].full_hash_) {
393 for(
unsigned int node=actual_node; node != 0; node=timers_[node].parent_timer) {
394 if ( cp.hash_ == timers_[node].full_hash_) {
396 for(; (
unsigned int)(actual_node) != node; actual_node=timers_[actual_node].parent_timer) {
397 WarningOut() <<
"Timer to close '" << cp.tag_ <<
"' do not match actual timer '" 398 << timers_[actual_node].tag() <<
"'. Force closing actual." << std::endl;
399 timers_[actual_node].stop(
true);
402 timers_[actual_node].stop(
false);
403 actual_node = timers_[actual_node].parent_timer;
406 if (actual_node == child_timer)
410 timers_[actual_node].resume();
418 timers_[actual_node].stop(
false);
419 actual_node = timers_[actual_node].parent_timer;
422 if (actual_node == child_timer)
426 timers_[actual_node].resume();
431 void Profiler::stop_timer(
int timer_index) {
435 if (timers_[timer_index].running()) {
436 ASSERT_EQ(timer_index, (
int)actual_node).error();
437 stop_timer(*timers_[timer_index].code_point_);
444 void Profiler::add_calls(
unsigned int n_calls) {
445 timers_[actual_node].call_count += n_calls-1;
451 if (!global_monitor_memory)
454 MemoryAlloc::malloc_map()[p] =
static_cast<int>(size);
455 timers_[actual_node].total_allocated_ += size;
456 timers_[actual_node].current_allocated_ += size;
457 timers_[actual_node].alloc_called++;
459 if (timers_[actual_node].current_allocated_ > timers_[actual_node].max_allocated_)
460 timers_[actual_node].max_allocated_ = timers_[actual_node].current_allocated_;
466 if (!global_monitor_memory)
469 int size =
sizeof(p);
470 if (MemoryAlloc::malloc_map()[(long)p] > 0) {
471 size = MemoryAlloc::malloc_map()[(long)p];
472 MemoryAlloc::malloc_map().erase((
long)p);
474 timers_[actual_node].total_deallocated_ += size;
475 timers_[actual_node].current_allocated_ -= size;
476 timers_[actual_node].dealloc_called++;
481 const int measurements = 100;
485 for (
unsigned int i = 1; i < measurements; i++) {
490 while ((t2 - t1) == 0) t2 =
TimePoint ();
496 return (result / measurements) * 1000;
500 std::string common_prefix( std::string a, std::string b ) {
501 if( a.size() > b.size() )
std::swap(a,b) ;
502 return std::string( a.begin(), std::mismatch( a.begin(), a.end(), b.begin() ).first ) ;
507 template<
typename ReduceFunctor>
508 void Profiler::add_timer_info(ReduceFunctor reduce,
nlohmann::json* holder,
int timer_idx,
double parent_time) {
511 Timer &timer = timers_[timer_idx];
512 ASSERT(timer_idx >=0)(timer_idx).error(
"Wrong timer index.");
513 ASSERT(timer.parent_timer >=0).error(
"Inconsistent tree.");
516 string filepath = timer.code_point_->file_;
519 #ifdef FLOW123D_SOURCE_DIR 520 string common_path = common_prefix (
string(FLOW123D_SOURCE_DIR), filepath);
521 filepath.erase (0, common_path.size());
528 double cumul_time_sum;
529 node[
"tag"] = timer.tag();
530 node[
"file-path"] = filepath;
531 node[
"file-line"] = timer.code_point_->line_;
532 node[
"function"] = timer.code_point_->func_;
533 cumul_time_sum = reduce(timer, node);
537 if (timer_idx == 0) parent_time = cumul_time_sum;
538 double percent = parent_time > 1.0e-10 ? cumul_time_sum / parent_time * 100.0 : 0.0;
539 node[
"percent"] = percent;
543 bool has_children =
false;
544 for (
unsigned int i = 0; i < Timer::max_n_childs; i++) {
545 if (timer.child_timers[i] != timer_no_child) {
546 add_timer_info (reduce, &children, timer.child_timers[i], cumul_time_sum);
556 node[
"children"] = children;
565 void save_nonmpi_metric (
nlohmann::json &node, T * ptr,
string name) {
566 node[name +
"-min"] = *ptr;
567 node[name +
"-max"] = *ptr;
568 node[name +
"-sum"] = *ptr;
571 std::shared_ptr<std::ostream> Profiler::get_default_output_stream() {
575 return make_shared<ofstream>(json_filepath.c_str());
579 #ifdef FLOW123D_HAVE_MPI 588 int mpi_rank, mpi_size;
595 bool temp_memory_monitoring = global_monitor_memory;
596 set_memory_monitoring(
false, petsc_monitor_memory);
608 int call_count = timer.call_count;
609 double cumul_time = timer.cumulative_time ();
611 long memory_allocated = (long)timer.total_allocated_;
612 long memory_deallocated = (
long)timer.total_deallocated_;
613 long memory_peak = (long)timer.max_allocated_;
615 int alloc_called = timer.alloc_called;
616 int dealloc_called = timer.dealloc_called;
619 save_mpi_metric<double>(node, comm, &cumul_time,
"cumul-time");
620 save_mpi_metric<int>(node, comm, &call_count,
"call-count");
622 save_mpi_metric<long>(node, comm, &memory_allocated,
"memory-alloc");
623 save_mpi_metric<long>(node, comm, &memory_deallocated,
"memory-dealloc");
624 save_mpi_metric<long>(node, comm, &memory_peak,
"memory-peak");
626 save_mpi_metric<int>(node, comm, &alloc_called,
"memory-alloc-called");
627 save_mpi_metric<int>(node, comm, &dealloc_called,
"memory-dealloc-called");
629 #ifdef FLOW123D_HAVE_PETSC 630 long petsc_memory_difference = (long)timer.petsc_memory_difference;
631 long petsc_peak_memory = (
long)timer.petsc_peak_memory;
632 save_mpi_metric<long>(node, comm, &petsc_memory_difference,
"memory-petsc-diff");
633 save_mpi_metric<long>(node, comm, &petsc_peak_memory,
"memory-petsc-peak");
634 #endif // FLOW123D_HAVE_PETSC 639 add_timer_info (reduce, &jsonChildren, 0, 0.0);
640 jsonRoot[
"children"] = jsonChildren;
641 output_header(jsonRoot, mpi_size);
652 const int FLOW123D_JSON_HUMAN_READABLE = 2;
654 os << jsonRoot.
dump(FLOW123D_JSON_HUMAN_READABLE) << endl;
656 }
catch (exception & e) {
658 ss <<
"nlohmann::json::dump error: " << e.what() <<
"\n";
659 THROW( ExcMessage() << EI_Message(ss.str()) );
663 set_memory_monitoring(temp_memory_monitoring, petsc_monitor_memory);
672 if (profiler_path ==
"") {
673 output(comm, *get_default_output_stream());
675 json_filepath = profiler_path;
676 std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
698 const int FLOW123D_MPI_SINGLE_PROCESS = 1;
699 output_header(jsonRoot, FLOW123D_MPI_SINGLE_PROCESS);
706 int call_count = timer.call_count;
707 double cumul_time = timer.cumulative_time ();
709 long memory_allocated = (long)timer.total_allocated_;
710 long memory_deallocated = (
long)timer.total_deallocated_;
711 long memory_peak = (long)timer.max_allocated_;
713 int alloc_called = timer.alloc_called;
714 int dealloc_called = timer.dealloc_called;
716 save_nonmpi_metric<double>(node, &cumul_time,
"cumul-time");
717 save_nonmpi_metric<int>(node, &call_count,
"call-count");
719 save_nonmpi_metric<long>(node, &memory_allocated,
"memory-alloc");
720 save_nonmpi_metric<long>(node, &memory_deallocated,
"memory-dealloc");
721 save_nonmpi_metric<long>(node, &memory_peak,
"memory-peak");
723 save_nonmpi_metric<int>(node, &alloc_called,
"memory-alloc-called");
724 save_nonmpi_metric<int>(node, &dealloc_called,
"memory-dealloc-called");
726 #ifdef FLOW123D_HAVE_PETSC 727 long petsc_memory_difference = (long)timer.petsc_memory_difference;
728 long petsc_peak_memory = (
long)timer.petsc_peak_memory;
729 save_nonmpi_metric<long>(node, &petsc_memory_difference,
"memory-petsc-diff");
730 save_nonmpi_metric<long>(node, &petsc_peak_memory,
"memory-petsc-peak");
731 #endif // FLOW123D_HAVE_PETSC 736 add_timer_info(reduce, &jsonChildren, 0, 0.0);
737 jsonRoot[
"children"] = jsonChildren;
744 const int FLOW123D_JSON_HUMAN_READABLE = 2;
746 os << jsonRoot.
dump(FLOW123D_JSON_HUMAN_READABLE) << endl;
748 }
catch (exception & e) {
750 ss <<
"nlohmann::json::dump error: " << e.what() <<
"\n";
751 THROW( ExcMessage() << EI_Message(ss.str()) );
757 if(profiler_path ==
"") {
758 output(*get_default_output_stream());
760 json_filepath = profiler_path;
761 std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
766 void Profiler::output_header (
nlohmann::json &root,
int mpi_size) {
767 time_t end_time = time(NULL);
769 const char format[] =
"%x %X";
770 char start_time_string[BUFSIZ] = {0};
771 strftime(start_time_string,
sizeof (start_time_string) - 1, format, localtime(&start_time));
773 char end_time_string[BUFSIZ] = {0};
774 strftime(end_time_string,
sizeof (end_time_string) - 1, format, localtime(&end_time));
777 root[
"program-name"] = flow_name_;
778 root[
"program-version"] = flow_version_;
779 root[
"program-branch"] = flow_branch_;
780 root[
"program-revision"] = flow_revision_;
781 root[
"program-build"] = flow_build_;
785 root[
"task-description"] = task_description_;
786 root[
"task-size"] = task_size_;
789 root[
"run-process-count"] = mpi_size;
790 root[
"run-started-at"] = start_time_string;
791 root[
"run-finished-at"] = end_time_string;
794 #ifdef FLOW123D_HAVE_PYTHON 797 if (json_filepath ==
"")
return;
806 #ifndef FLOW123D_HAVE_CYGWIN 808 PyObject * python_module = PythonLoader::load_module_by_name (
"profiler.profiler_formatter_module");
812 PyObject * convert_method = PythonLoader::get_callable (python_module,
"convert" );
814 int argument_index = 0;
815 PyObject * arguments = PyTuple_New (3);
818 PyObject * tmp = PyUnicode_FromString (json_filepath.c_str());
819 PyTuple_SetItem (arguments, argument_index++, tmp);
822 tmp = PyUnicode_FromString ((json_filepath + output_file_suffix).c_str());
823 PyTuple_SetItem (arguments, argument_index++, tmp);
826 tmp = PyUnicode_FromString (formatter.c_str());
827 PyTuple_SetItem (arguments, argument_index++, tmp);
830 PyObject_CallObject (convert_method, arguments);
832 PythonLoader::check_error();
837 MessageOut() <<
"# Note: converting json profiler reports is not" 838 <<
" supported under Windows or Cygwin environment for now.\n" 839 <<
"# You can use python script located in bin/python folder" 840 <<
" in order to convert json report to txt or csv format.\n" 841 <<
"python profiler_formatter_script.py --input \"" << json_filepath
842 <<
"\" --output \"profiler.txt\"" << std::endl;
843 #endif // FLOW123D_HAVE_CYGWIN 849 #endif // FLOW123D_HAVE_PYTHON 855 .error(
"Forbidden to uninitialize the Profiler when actual timer is not zero.");
857 set_memory_monitoring(
false,
false);
862 bool Profiler::global_monitor_memory =
false;
863 bool Profiler::petsc_monitor_memory =
true;
864 void Profiler::set_memory_monitoring(
const bool global_monitor,
const bool petsc_monitor) {
865 global_monitor_memory = global_monitor;
866 petsc_monitor_memory = petsc_monitor;
869 bool Profiler::get_global_memory_monitoring() {
870 return global_monitor_memory;
873 bool Profiler::get_petsc_memory_monitoring() {
874 return petsc_monitor_memory;
877 unordered_map_with_alloc & MemoryAlloc::malloc_map() {
878 static unordered_map_with_alloc static_malloc_map;
879 return static_malloc_map;
882 void * Profiler::operator
new (
size_t size) {
883 return malloc (size);
886 void Profiler::operator
delete (
void* p) {
891 void * p = malloc(size);
897 void * p = malloc(size);
902 void *
operator new[] (std::size_t size,
const std::nothrow_t&)
throw() {
903 void * p = malloc(size);
908 void operator delete(
void *p)
throw() {
913 void operator delete[](
void *p)
throw() {
918 #else // def FLOW123D_DEBUG_PROFILER 937 .error(
"Forbidden to uninitialize the Profiler when actual timer is not zero.");
938 set_memory_monitoring(
false,
false);
946 #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.
#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)