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() {
610 char filename[PATH_MAX];
611 strftime(filename,
sizeof (filename) - 1,
"profiler_info_%y.%m.%d_%H-%M-%S.log.json", localtime(&start_time));
615 return make_shared<ofstream>(json_filepath.c_str());
619 #ifdef FLOW123D_HAVE_MPI 621 void save_mpi_metric (property_tree::ptree &node,
MPI_Comm comm, T * ptr,
string name) {
628 int mpi_rank, mpi_size;
635 bool temp_memory_monitoring = global_monitor_memory;
636 set_memory_monitoring(
false, petsc_monitor_memory);
642 property_tree::ptree root, children;
643 output_header (root, mpi_size);
648 auto reduce = [=] (
Timer &timer, property_tree::ptree &node) ->
double {
649 int call_count = timer.call_count;
650 double cumul_time = timer.cumulative_time ();
652 long memory_allocated = (long)timer.total_allocated_;
653 long memory_deallocated = (
long)timer.total_deallocated_;
654 long memory_peak = (long)timer.max_allocated_;
656 int alloc_called = timer.alloc_called;
657 int dealloc_called = timer.dealloc_called;
660 save_mpi_metric<double>(node, comm, &cumul_time,
"cumul-time");
661 save_mpi_metric<int>(node, comm, &call_count,
"call-count");
663 save_mpi_metric<long>(node, comm, &memory_allocated,
"memory-alloc");
664 save_mpi_metric<long>(node, comm, &memory_deallocated,
"memory-dealloc");
665 save_mpi_metric<long>(node, comm, &memory_peak,
"memory-peak");
667 save_mpi_metric<int>(node, comm, &alloc_called,
"memory-alloc-called");
668 save_mpi_metric<int>(node, comm, &dealloc_called,
"memory-dealloc-called");
670 #ifdef FLOW123D_HAVE_PETSC 671 long petsc_memory_difference = (long)timer.petsc_memory_difference;
672 long petsc_peak_memory = (
long)timer.petsc_peak_memory;
673 save_mpi_metric<long>(node, comm, &petsc_memory_difference,
"memory-petsc-diff");
674 save_mpi_metric<long>(node, comm, &petsc_peak_memory,
"memory-petsc-peak");
675 #endif // FLOW123D_HAVE_PETSC 680 add_timer_info (reduce, &children, 0, 0.0);
681 root.add_child (
"children", children);
692 const int FLOW123D_JSON_HUMAN_READABLE = 1;
694 property_tree::write_json (os, root, FLOW123D_JSON_HUMAN_READABLE);
695 }
catch (property_tree::json_parser::json_parser_error & e) {
697 ss <<
"Throw json_parser_error: " << e.message() <<
"\nIn file: " << e.filename() <<
", at line " << e.line() <<
"\n";
698 THROW( ExcMessage() << EI_Message(ss.str()) );
702 set_memory_monitoring(temp_memory_monitoring, petsc_monitor_memory);
710 output(comm, *get_default_output_stream());
725 property_tree::ptree root, children;
730 const int FLOW123D_MPI_SINGLE_PROCESS = 1;
731 output_header (root, FLOW123D_MPI_SINGLE_PROCESS);
737 auto reduce = [=] (
Timer &timer, property_tree::ptree &node) ->
double {
738 int call_count = timer.call_count;
739 double cumul_time = timer.cumulative_time ();
741 long memory_allocated = (long)timer.total_allocated_;
742 long memory_deallocated = (
long)timer.total_deallocated_;
743 long memory_peak = (long)timer.max_allocated_;
745 int alloc_called = timer.alloc_called;
746 int dealloc_called = timer.dealloc_called;
748 save_nonmpi_metric<double>(node, &cumul_time,
"cumul-time");
749 save_nonmpi_metric<int>(node, &call_count,
"call-count");
751 save_nonmpi_metric<long>(node, &memory_allocated,
"memory-alloc");
752 save_nonmpi_metric<long>(node, &memory_deallocated,
"memory-dealloc");
753 save_nonmpi_metric<long>(node, &memory_peak,
"memory-peak");
755 save_nonmpi_metric<int>(node, &alloc_called,
"memory-alloc-called");
756 save_nonmpi_metric<int>(node, &dealloc_called,
"memory-dealloc-called");
758 #ifdef FLOW123D_HAVE_PETSC 759 long petsc_memory_difference = (long)timer.petsc_memory_difference;
760 long petsc_peak_memory = (
long)timer.petsc_peak_memory;
761 save_nonmpi_metric<long>(node, &petsc_memory_difference,
"memory-petsc-diff");
762 save_nonmpi_metric<long>(node, &petsc_peak_memory,
"memory-petsc-peak");
763 #endif // FLOW123D_HAVE_PETSC 768 add_timer_info (reduce, &children, 0, 0.0);
769 root.add_child (
"children", children);
777 const int FLOW123D_JSON_HUMAN_READABLE = 1;
779 property_tree::write_json (os, root, FLOW123D_JSON_HUMAN_READABLE);
780 }
catch (property_tree::json_parser::json_parser_error & e) {
782 ss <<
"Throw json_parser_error: " << e.message() <<
"\nIn file: " << e.filename() <<
", at line " << e.line() <<
"\n";
783 THROW( ExcMessage() << EI_Message(ss.str()) );
789 output(*get_default_output_stream());
792 void Profiler::output_header (property_tree::ptree &root,
int mpi_size) {
793 time_t end_time = time(NULL);
795 const char format[] =
"%x %X";
796 char start_time_string[BUFSIZ] = {0};
797 strftime(start_time_string,
sizeof (start_time_string) - 1, format, localtime(&start_time));
799 char end_time_string[BUFSIZ] = {0};
800 strftime(end_time_string,
sizeof (end_time_string) - 1, format, localtime(&end_time));
804 root.put (
"program-name", flow_name_);
805 root.put (
"program-version", flow_version_);
806 root.put (
"program-branch", flow_branch_);
807 root.put (
"program-revision", flow_revision_);
808 root.put (
"program-build", flow_build_);
811 #ifdef FLOW123D_SOURCE_DIR 815 root.put (
"task-description", task_description_);
816 root.put (
"task-size", task_size_);
819 root.put (
"run-process-count", mpi_size);
820 root.put (
"run-started-at", start_time_string);
821 root.put (
"run-finished-at", end_time_string);
824 #ifdef FLOW123D_HAVE_PYTHON 827 if (json_filepath==
"")
return;
836 #ifndef FLOW123D_HAVE_CYGWIN 838 PyObject * python_module = PythonLoader::load_module_by_name (
"profiler.profiler_formatter_module");
842 PyObject * convert_method = PythonLoader::get_callable (python_module,
"convert" );
844 int argument_index = 0;
845 PyObject * arguments = PyTuple_New (3);
848 PyObject * tmp = PyUnicode_FromString (json_filepath.c_str());
849 PyTuple_SetItem (arguments, argument_index++, tmp);
852 tmp = PyUnicode_FromString ((json_filepath + output_file_suffix).c_str());
853 PyTuple_SetItem (arguments, argument_index++, tmp);
856 tmp = PyUnicode_FromString (formatter.c_str());
857 PyTuple_SetItem (arguments, argument_index++, tmp);
860 PyObject_CallObject (convert_method, arguments);
862 PythonLoader::check_error();
867 MessageOut() <<
"# Note: converting json profiler reports is not" 868 <<
" supported under Windows or Cygwin environment for now.\n" 869 <<
"# You can use python script located in bin/python folder" 870 <<
" in order to convert json report to txt or csv format.\n" 871 <<
"python profiler_formatter_script.py --input \"" << json_filepath
872 <<
"\" --output \"profiler.txt\"" << std::endl;
873 #endif // FLOW123D_HAVE_CYGWIN 879 #endif // FLOW123D_HAVE_PYTHON 884 ASSERT(_instance->actual_node==0)(_instance->timers_[_instance->actual_node].tag())
885 .error(
"Forbidden to uninitialize the Profiler when actual timer is not zero.");
886 _instance->stop_timer(0);
887 set_memory_monitoring(
false,
false);
892 bool Profiler::global_monitor_memory =
false;
893 bool Profiler::petsc_monitor_memory =
true;
894 void Profiler::set_memory_monitoring(
const bool global_monitor,
const bool petsc_monitor) {
895 global_monitor_memory = global_monitor;
896 petsc_monitor_memory = petsc_monitor;
899 bool Profiler::get_global_memory_monitoring() {
900 return global_monitor_memory;
903 bool Profiler::get_petsc_memory_monitoring() {
904 return petsc_monitor_memory;
907 unordered_map_with_alloc & MemoryAlloc::malloc_map() {
908 static unordered_map_with_alloc static_malloc_map;
909 return static_malloc_map;
912 void * Profiler::operator
new (
size_t size) {
913 return malloc (size);
916 void Profiler::operator
delete (
void* p) {
921 void * p = malloc(size);
927 void * p = malloc(size);
932 void *
operator new[] (std::size_t size,
const std::nothrow_t&)
throw() {
933 void * p = malloc(size);
938 void operator delete(
void *p)
throw() {
943 void operator delete[](
void *p)
throw() {
948 #else // def FLOW123D_DEBUG_PROFILER 955 Profiler* Profiler::_instance = NULL;
958 if (_instance == NULL) {
960 set_memory_monitoring(
true,
true);
966 ASSERT(_instance->actual_node==0)(_instance->timers_[_instance->actual_node].tag())
967 .error(
"Forbidden to uninitialize the Profiler when actual timer is not zero.");
968 set_memory_monitoring(
false,
false);
969 _instance->stop_timer(0);
976 #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)