24 #include <sys/param.h> 26 #ifdef FLOW123D_HAVE_PYTHON 28 #endif // FLOW123D_HAVE_PYTHON 34 #include <boost/format.hpp> 35 #include <boost/property_tree/ptree.hpp> 36 #include <boost/property_tree/json_parser.hpp> 37 #include <boost/unordered_map.hpp> 45 namespace property_tree = boost::property_tree;
105 #ifdef FLOW123D_DEBUG_PROFILER 110 const int timer_no_child=-1;
112 Timer::Timer(
const CodePoint &cp,
int parent)
118 full_hash_(cp.hash_),
119 hash_idx_(cp.hash_idx_),
120 parent_timer(parent),
122 total_deallocated_(0),
124 current_allocated_(0),
127 #ifdef FLOW123D_HAVE_PETSC 128 , petsc_start_memory(0),
129 petsc_end_memory (0),
130 petsc_memory_difference(0),
131 petsc_peak_memory(0),
132 petsc_local_peak_memory(0)
133 #endif // FLOW123D_HAVE_PETSC 135 for(
unsigned int i=0; i< max_n_childs ;i++) child_timers[i]=timer_no_child;
143 os <<
" Timer: " << timer.tag() << endl;
144 os <<
" malloc: " << timer.total_allocated_ << endl;
145 os <<
" dalloc: " << timer.total_deallocated_ << endl;
146 #ifdef FLOW123D_HAVE_PETSC 147 os <<
" start: " << timer.petsc_start_memory << endl;
148 os <<
" stop : " << timer.petsc_end_memory << endl;
149 os <<
" diff : " << timer.petsc_memory_difference <<
" (" << timer.petsc_end_memory - timer.petsc_start_memory <<
")" << endl;
150 os <<
" peak : " << timer.petsc_peak_memory <<
" (" << timer.petsc_local_peak_memory <<
")" << endl;
151 #endif // FLOW123D_HAVE_PETSC 157 double Timer::cumulative_time()
const {
161 void Profiler::accept_from_child(
Timer &parent,
Timer &child) {
163 for (
unsigned int i = 0; i < Timer::max_n_childs; i++) {
164 child_timer = child.child_timers[i];
165 if (child_timer != timer_no_child) {
167 accept_from_child(child, timers_[child_timer]);
171 parent.total_allocated_ += child.total_allocated_;
172 parent.total_deallocated_ += child.total_deallocated_;
173 parent.alloc_called += child.alloc_called;
174 parent.dealloc_called += child.dealloc_called;
176 #ifdef FLOW123D_HAVE_PETSC 177 if (petsc_monitor_memory) {
179 parent.petsc_memory_difference += child.petsc_memory_difference;
180 parent.current_allocated_ += child.current_allocated_;
184 parent.petsc_peak_memory =
max(parent.petsc_peak_memory, child.petsc_peak_memory);
186 #endif // FLOW123D_HAVE_PETSC 188 parent.max_allocated_ =
max(parent.max_allocated_, child.max_allocated_);
192 void Timer::pause() {
193 #ifdef FLOW123D_HAVE_PETSC 194 if (Profiler::get_petsc_memory_monitoring()) {
196 PetscMemoryGetMaximumUsage(&petsc_local_peak_memory);
197 if (petsc_peak_memory < petsc_local_peak_memory)
198 petsc_peak_memory = petsc_local_peak_memory;
200 #endif // FLOW123D_HAVE_PETSC 203 void Timer::resume() {
204 #ifdef FLOW123D_HAVE_PETSC 205 if (Profiler::get_petsc_memory_monitoring()) {
208 PetscMemorySetGetMaximumUsage();
210 #endif // FLOW123D_HAVE_PETSC 214 #ifdef FLOW123D_HAVE_PETSC 215 if (Profiler::get_petsc_memory_monitoring()) {
218 PetscMemorySetGetMaximumUsage();
219 PetscMemoryGetCurrentUsage (&petsc_start_memory);
221 #endif // FLOW123D_HAVE_PETSC 223 if (start_count == 0) {
233 #ifdef FLOW123D_HAVE_PETSC 234 if (Profiler::get_petsc_memory_monitoring()) {
236 PetscMemoryGetCurrentUsage (&petsc_end_memory);
237 petsc_memory_difference += petsc_end_memory - petsc_start_memory;
240 PetscMemoryGetMaximumUsage(&petsc_local_peak_memory);
241 if (petsc_peak_memory < petsc_local_peak_memory)
242 petsc_peak_memory = petsc_local_peak_memory;
244 #endif // FLOW123D_HAVE_PETSC 246 if (forced) start_count=1;
248 if (start_count == 1) {
249 cumul_time += (
TimePoint() - start_time);
260 void Timer::add_child(
int child_index,
const Timer &child)
262 unsigned int idx = child.hash_idx_;
263 if (child_timers[idx] != timer_no_child) {
267 i=( i < max_n_childs ? i+1 : 0);
268 }
while (i!=idx && child_timers[i] != timer_no_child);
269 ASSERT(i!=idx)(tag()).error(
"Too many children of the timer");
273 child_timers[idx] = child_index;
278 string Timer::code_point_str()
const {
279 return boost::str(
boost::format(
"%s:%d, %s()") % code_point_->file_ % code_point_->line_ % code_point_->func_ );
289 if (_instance == NULL) {
290 MemoryAlloc::malloc_map().reserve(Profiler::malloc_map_reserve);
297 static CONSTEXPR_ CodePoint main_cp = CODE_POINT(
"Whole Program");
299 const long Profiler::malloc_map_reserve = 100 * 1000;
300 CodePoint Profiler::null_code_point = CodePoint(
"__no_tag__",
"__no_file__",
"__no_func__", 0);
304 set_memory_monitoring(
true,
true);
311 start_time( time(NULL) ),
315 #ifdef FLOW123D_DEBUG_PROFILER 316 timers_.push_back(
Timer(main_cp, 0) );
323 void Profiler::propagate_timers() {
324 for (
unsigned int i = 0; i < Timer::max_n_childs; i++) {
325 unsigned int child_timer = timers_[0].child_timers[i];
326 if ((
signed int)child_timer != timer_no_child) {
328 accept_from_child(timers_[0], timers_[child_timer]);
336 task_description_ = description;
343 flow_name_ = program_name;
344 flow_version_ = program_version;
345 flow_branch_ = branch;
346 flow_revision_ = revision;
352 int Profiler::start_timer(
const CodePoint &cp) {
353 unsigned int parent_node = actual_node;
355 int child_idx = find_child(cp);
359 child_idx=timers_.size();
360 timers_.push_back(
Timer(cp, actual_node) );
361 timers_[actual_node].add_child(child_idx , timers_.back() );
363 actual_node=child_idx;
366 timers_[parent_node].pause();
368 timers_[actual_node].start();
375 int Profiler::find_child(
const CodePoint &cp) {
376 Timer &timer =timers_[actual_node];
377 unsigned int idx = cp.hash_idx_;
378 unsigned int child_idx;
380 if (timer.child_timers[idx] == timer_no_child)
break;
382 child_idx=timer.child_timers[idx];
383 ASSERT_LT(child_idx, timers_.size()).error();
384 if (timers_[child_idx].full_hash_ == cp.hash_)
return child_idx;
385 idx = ( (
unsigned int)(idx)==(Timer::max_n_childs - 1) ? 0 : idx+1 );
386 }
while ( (
unsigned int)(idx) != cp.hash_idx_ );
392 void Profiler::stop_timer(
const CodePoint &cp) {
393 #ifdef FLOW123D_DEBUG 395 Timer &timer=timers_[actual_node];
396 for(
unsigned int i=0; i < Timer::max_n_childs; i++)
397 if (timer.child_timers[i] != timer_no_child)
398 ASSERT(! timers_[timer.child_timers[i]].running())(timers_[timer.child_timers[i]].tag())(timer.tag())
399 .error(
"Child timer running while closing timer.");
401 unsigned int child_timer = actual_node;
402 if ( cp.hash_ != timers_[actual_node].full_hash_) {
404 for(
unsigned int node=actual_node; node != 0; node=timers_[node].parent_timer) {
405 if ( cp.hash_ == timers_[node].full_hash_) {
407 for(; (
unsigned int)(actual_node) != node; actual_node=timers_[actual_node].parent_timer) {
408 WarningOut() <<
"Timer to close '" << cp.tag_ <<
"' do not match actual timer '" 409 << timers_[actual_node].tag() <<
"'. Force closing actual." << std::endl;
410 timers_[actual_node].stop(
true);
413 timers_[actual_node].stop(
false);
414 actual_node = timers_[actual_node].parent_timer;
417 if (actual_node == child_timer)
421 timers_[actual_node].resume();
429 timers_[actual_node].stop(
false);
430 actual_node = timers_[actual_node].parent_timer;
433 if (actual_node == child_timer)
437 timers_[actual_node].resume();
442 void Profiler::stop_timer(
int timer_index) {
446 if (timers_[timer_index].running()) {
447 ASSERT_EQ(timer_index, (
int)actual_node).error();
448 stop_timer(*timers_[timer_index].code_point_);
455 void Profiler::add_calls(
unsigned int n_calls) {
456 timers_[actual_node].call_count += n_calls-1;
462 if (!global_monitor_memory)
465 MemoryAlloc::malloc_map()[p] =
static_cast<int>(size);
466 timers_[actual_node].total_allocated_ += size;
467 timers_[actual_node].current_allocated_ += size;
468 timers_[actual_node].alloc_called++;
470 if (timers_[actual_node].current_allocated_ > timers_[actual_node].max_allocated_)
471 timers_[actual_node].max_allocated_ = timers_[actual_node].current_allocated_;
477 if (!global_monitor_memory)
480 int size =
sizeof(p);
481 if (MemoryAlloc::malloc_map()[(long)p] > 0) {
482 size = MemoryAlloc::malloc_map()[(long)p];
483 MemoryAlloc::malloc_map().erase((
long)p);
485 timers_[actual_node].total_deallocated_ += size;
486 timers_[actual_node].current_allocated_ -= size;
487 timers_[actual_node].dealloc_called++;
492 const int measurements = 100;
496 for (
unsigned int i = 1; i < measurements; i++) {
501 while ((t2 - t1) == 0) t2 =
TimePoint ();
507 return (result / measurements) * 1000;
511 std::string common_prefix( std::string a, std::string b ) {
512 if( a.size() > b.size() )
std::swap(a,b) ;
513 return std::string( a.begin(), std::mismatch( a.begin(), a.end(), b.begin() ).first ) ;
518 template<
typename ReduceFunctor>
519 void Profiler::add_timer_info(ReduceFunctor reduce, property_tree::ptree* holder,
int timer_idx,
double parent_time) {
522 Timer &timer = timers_[timer_idx];
523 ASSERT(timer_idx >=0)(timer_idx).error(
"Wrong timer index.");
524 ASSERT(timer.parent_timer >=0).error(
"Inconsistent tree.");
527 string filepath = timer.code_point_->file_;
530 #ifdef FLOW123D_SOURCE_DIR 531 string common_path = common_prefix (
string(FLOW123D_SOURCE_DIR), filepath);
532 filepath.erase (0, common_path.size());
538 property_tree::ptree node;
539 double cumul_time_sum;
540 node.put (
"tag", (timer.tag()) );
541 node.put (
"file-path", (filepath) );
542 node.put (
"file-line", (timer.code_point_->line_) );
543 node.put (
"function", (timer.code_point_->func_) );
544 cumul_time_sum = reduce (timer, node);
548 if (timer_idx == 0) parent_time = cumul_time_sum;
549 double percent = parent_time > 1.0e-10 ? cumul_time_sum / parent_time * 100.0 : 0.0;
550 node.put<
double> (
"percent", percent);
581 property_tree::ptree children;
582 bool has_children =
false;
583 for (
unsigned int i = 0; i < Timer::max_n_childs; i++) {
584 if (timer.child_timers[i] != timer_no_child) {
585 add_timer_info (reduce, &children, timer.child_timers[i], cumul_time_sum);
595 node.add_child (
"children", children);
598 holder->push_back (std::make_pair (
"", node));
603 void save_nonmpi_metric (property_tree::ptree &node, T * ptr,
string name) {
604 node.put (name+
"-min", *ptr);
605 node.put (name+
"-max", *ptr);
606 node.put (name+
"-sum", *ptr);
609 std::shared_ptr<std::ostream> Profiler::get_default_output_stream() {
613 return make_shared<ofstream>(json_filepath.c_str());
617 #ifdef FLOW123D_HAVE_MPI 619 void save_mpi_metric (property_tree::ptree &node,
MPI_Comm comm, T * ptr,
string name) {
626 int mpi_rank, mpi_size;
633 bool temp_memory_monitoring = global_monitor_memory;
634 set_memory_monitoring(
false, petsc_monitor_memory);
640 property_tree::ptree root, children;
641 output_header (root, mpi_size);
646 auto reduce = [=] (
Timer &timer, property_tree::ptree &node) ->
double {
647 int call_count = timer.call_count;
648 double cumul_time = timer.cumulative_time ();
650 long memory_allocated = (long)timer.total_allocated_;
651 long memory_deallocated = (
long)timer.total_deallocated_;
652 long memory_peak = (long)timer.max_allocated_;
654 int alloc_called = timer.alloc_called;
655 int dealloc_called = timer.dealloc_called;
658 save_mpi_metric<double>(node, comm, &cumul_time,
"cumul-time");
659 save_mpi_metric<int>(node, comm, &call_count,
"call-count");
661 save_mpi_metric<long>(node, comm, &memory_allocated,
"memory-alloc");
662 save_mpi_metric<long>(node, comm, &memory_deallocated,
"memory-dealloc");
663 save_mpi_metric<long>(node, comm, &memory_peak,
"memory-peak");
665 save_mpi_metric<int>(node, comm, &alloc_called,
"memory-alloc-called");
666 save_mpi_metric<int>(node, comm, &dealloc_called,
"memory-dealloc-called");
668 #ifdef FLOW123D_HAVE_PETSC 669 long petsc_memory_difference = (long)timer.petsc_memory_difference;
670 long petsc_peak_memory = (
long)timer.petsc_peak_memory;
671 save_mpi_metric<long>(node, comm, &petsc_memory_difference,
"memory-petsc-diff");
672 save_mpi_metric<long>(node, comm, &petsc_peak_memory,
"memory-petsc-peak");
673 #endif // FLOW123D_HAVE_PETSC 678 add_timer_info (reduce, &children, 0, 0.0);
679 root.add_child (
"children", children);
690 const int FLOW123D_JSON_HUMAN_READABLE = 1;
692 property_tree::write_json (os, root, FLOW123D_JSON_HUMAN_READABLE);
693 }
catch (property_tree::json_parser::json_parser_error & e) {
695 ss <<
"Throw json_parser_error: " << e.message() <<
"\nIn file: " << e.filename() <<
", at line " << e.line() <<
"\n";
696 THROW( ExcMessage() << EI_Message(ss.str()) );
700 set_memory_monitoring(temp_memory_monitoring, petsc_monitor_memory);
709 if (profiler_path ==
"") {
710 output(comm, *get_default_output_stream());
712 json_filepath = profiler_path;
713 std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
730 property_tree::ptree root, children;
735 const int FLOW123D_MPI_SINGLE_PROCESS = 1;
736 output_header (root, FLOW123D_MPI_SINGLE_PROCESS);
742 auto reduce = [=] (
Timer &timer, property_tree::ptree &node) ->
double {
743 int call_count = timer.call_count;
744 double cumul_time = timer.cumulative_time ();
746 long memory_allocated = (long)timer.total_allocated_;
747 long memory_deallocated = (
long)timer.total_deallocated_;
748 long memory_peak = (long)timer.max_allocated_;
750 int alloc_called = timer.alloc_called;
751 int dealloc_called = timer.dealloc_called;
753 save_nonmpi_metric<double>(node, &cumul_time,
"cumul-time");
754 save_nonmpi_metric<int>(node, &call_count,
"call-count");
756 save_nonmpi_metric<long>(node, &memory_allocated,
"memory-alloc");
757 save_nonmpi_metric<long>(node, &memory_deallocated,
"memory-dealloc");
758 save_nonmpi_metric<long>(node, &memory_peak,
"memory-peak");
760 save_nonmpi_metric<int>(node, &alloc_called,
"memory-alloc-called");
761 save_nonmpi_metric<int>(node, &dealloc_called,
"memory-dealloc-called");
763 #ifdef FLOW123D_HAVE_PETSC 764 long petsc_memory_difference = (long)timer.petsc_memory_difference;
765 long petsc_peak_memory = (
long)timer.petsc_peak_memory;
766 save_nonmpi_metric<long>(node, &petsc_memory_difference,
"memory-petsc-diff");
767 save_nonmpi_metric<long>(node, &petsc_peak_memory,
"memory-petsc-peak");
768 #endif // FLOW123D_HAVE_PETSC 773 add_timer_info (reduce, &children, 0, 0.0);
774 root.add_child (
"children", children);
782 const int FLOW123D_JSON_HUMAN_READABLE = 1;
784 property_tree::write_json (os, root, FLOW123D_JSON_HUMAN_READABLE);
785 }
catch (property_tree::json_parser::json_parser_error & e) {
787 ss <<
"Throw json_parser_error: " << e.message() <<
"\nIn file: " << e.filename() <<
", at line " << e.line() <<
"\n";
788 THROW( ExcMessage() << EI_Message(ss.str()) );
794 if(profiler_path ==
"") {
795 output(*get_default_output_stream());
797 json_filepath = profiler_path;
798 std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
803 void Profiler::output_header (property_tree::ptree &root,
int mpi_size) {
804 time_t end_time = time(NULL);
806 const char format[] =
"%x %X";
807 char start_time_string[BUFSIZ] = {0};
808 strftime(start_time_string,
sizeof (start_time_string) - 1, format, localtime(&start_time));
810 char end_time_string[BUFSIZ] = {0};
811 strftime(end_time_string,
sizeof (end_time_string) - 1, format, localtime(&end_time));
815 root.put (
"program-name", flow_name_);
816 root.put (
"program-version", flow_version_);
817 root.put (
"program-branch", flow_branch_);
818 root.put (
"program-revision", flow_revision_);
819 root.put (
"program-build", flow_build_);
822 #ifdef FLOW123D_SOURCE_DIR 826 root.put (
"task-description", task_description_);
827 root.put (
"task-size", task_size_);
830 root.put (
"run-process-count", mpi_size);
831 root.put (
"run-started-at", start_time_string);
832 root.put (
"run-finished-at", end_time_string);
835 #ifdef FLOW123D_HAVE_PYTHON 838 if (json_filepath ==
"")
return;
847 #ifndef FLOW123D_HAVE_CYGWIN 849 PyObject * python_module = PythonLoader::load_module_by_name (
"profiler.profiler_formatter_module");
853 PyObject * convert_method = PythonLoader::get_callable (python_module,
"convert" );
855 int argument_index = 0;
856 PyObject * arguments = PyTuple_New (3);
859 PyObject * tmp = PyUnicode_FromString (json_filepath.c_str());
860 PyTuple_SetItem (arguments, argument_index++, tmp);
863 tmp = PyUnicode_FromString ((json_filepath + output_file_suffix).c_str());
864 PyTuple_SetItem (arguments, argument_index++, tmp);
867 tmp = PyUnicode_FromString (formatter.c_str());
868 PyTuple_SetItem (arguments, argument_index++, tmp);
871 PyObject_CallObject (convert_method, arguments);
873 PythonLoader::check_error();
878 MessageOut() <<
"# Note: converting json profiler reports is not" 879 <<
" supported under Windows or Cygwin environment for now.\n" 880 <<
"# You can use python script located in bin/python folder" 881 <<
" in order to convert json report to txt or csv format.\n" 882 <<
"python profiler_formatter_script.py --input \"" << json_filepath
883 <<
"\" --output \"profiler.txt\"" << std::endl;
884 #endif // FLOW123D_HAVE_CYGWIN 890 #endif // FLOW123D_HAVE_PYTHON 895 ASSERT(_instance->actual_node==0)(_instance->timers_[_instance->actual_node].tag())
896 .error(
"Forbidden to uninitialize the Profiler when actual timer is not zero.");
897 _instance->stop_timer(0);
898 set_memory_monitoring(
false,
false);
903 bool Profiler::global_monitor_memory =
false;
904 bool Profiler::petsc_monitor_memory =
true;
905 void Profiler::set_memory_monitoring(
const bool global_monitor,
const bool petsc_monitor) {
906 global_monitor_memory = global_monitor;
907 petsc_monitor_memory = petsc_monitor;
910 bool Profiler::get_global_memory_monitoring() {
911 return global_monitor_memory;
914 bool Profiler::get_petsc_memory_monitoring() {
915 return petsc_monitor_memory;
918 unordered_map_with_alloc & MemoryAlloc::malloc_map() {
919 static unordered_map_with_alloc static_malloc_map;
920 return static_malloc_map;
923 void * Profiler::operator
new (
size_t size) {
924 return malloc (size);
927 void Profiler::operator
delete (
void* p) {
932 void * p = malloc(size);
938 void * p = malloc(size);
943 void *
operator new[] (std::size_t size,
const std::nothrow_t&)
throw() {
944 void * p = malloc(size);
949 void operator delete(
void *p)
throw() {
954 void operator delete[](
void *p)
throw() {
959 #else // def FLOW123D_DEBUG_PROFILER 966 Profiler* Profiler::_instance = NULL;
969 if (_instance == NULL) {
971 set_memory_monitoring(
true,
true);
977 ASSERT(_instance->actual_node==0)(_instance->timers_[_instance->actual_node].tag())
978 .error(
"Forbidden to uninitialize the Profiler when actual timer is not zero.");
979 set_memory_monitoring(
false,
false);
980 _instance->stop_timer(0);
987 #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)
#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 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)
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)