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_ );
287 if (_instance != NULL) {
294 if (_instance == NULL) {
295 MemoryAlloc::malloc_map().reserve(Profiler::malloc_map_reserve);
304 const long Profiler::malloc_map_reserve = 100 * 1000;
309 start_time( time(NULL) ),
313 static CONSTEXPR_ CodePoint main_cp = CODE_POINT(
"Whole Program");
314 set_memory_monitoring(
true,
true);
315 #ifdef FLOW123D_DEBUG_PROFILER 316 MemoryAlloc::malloc_map().reserve(Profiler::malloc_map_reserve);
317 timers_.push_back(
Timer(main_cp, 0) );
324 void Profiler::propagate_timers() {
325 for (
unsigned int i = 0; i < Timer::max_n_childs; i++) {
326 unsigned int child_timer = timers_[0].child_timers[i];
327 if ((
signed int)child_timer != timer_no_child) {
329 accept_from_child(timers_[0], timers_[child_timer]);
337 task_description_ = description;
344 flow_name_ = program_name;
345 flow_version_ = program_version;
346 flow_branch_ = branch;
347 flow_revision_ = revision;
353 int Profiler::start_timer(
const CodePoint &cp) {
354 unsigned int parent_node = actual_node;
356 int child_idx = find_child(cp);
360 child_idx=timers_.size();
361 timers_.push_back(
Timer(cp, actual_node) );
362 timers_[actual_node].add_child(child_idx , timers_.back() );
364 actual_node=child_idx;
367 timers_[parent_node].pause();
369 timers_[actual_node].start();
376 int Profiler::find_child(
const CodePoint &cp) {
377 Timer &timer =timers_[actual_node];
378 unsigned int idx = cp.hash_idx_;
379 unsigned int child_idx;
381 if (timer.child_timers[idx] == timer_no_child)
break;
383 child_idx=timer.child_timers[idx];
384 ASSERT_LT(child_idx, timers_.size()).error();
385 if (timers_[child_idx].full_hash_ == cp.hash_)
return child_idx;
386 idx = ( (
unsigned int)(idx)==(Timer::max_n_childs - 1) ? 0 : idx+1 );
387 }
while ( (
unsigned int)(idx) != cp.hash_idx_ );
393 void Profiler::stop_timer(
const CodePoint &cp) {
394 #ifdef FLOW123D_DEBUG 396 Timer &timer=timers_[actual_node];
397 for(
unsigned int i=0; i < Timer::max_n_childs; i++)
398 if (timer.child_timers[i] != timer_no_child)
399 ASSERT(! timers_[timer.child_timers[i]].running())(timers_[timer.child_timers[i]].tag())(timer.tag())
400 .error(
"Child timer running while closing timer.");
402 unsigned int child_timer = actual_node;
403 if ( cp.hash_ != timers_[actual_node].full_hash_) {
405 for(
unsigned int node=actual_node; node != 0; node=timers_[node].parent_timer) {
406 if ( cp.hash_ == timers_[node].full_hash_) {
408 for(; (
unsigned int)(actual_node) != node; actual_node=timers_[actual_node].parent_timer) {
409 WarningOut() <<
"Timer to close '" << cp.tag_ <<
"' do not match actual timer '" 410 << timers_[actual_node].tag() <<
"'. Force closing actual." << std::endl;
411 timers_[actual_node].stop(
true);
414 timers_[actual_node].stop(
false);
415 actual_node = timers_[actual_node].parent_timer;
418 if (actual_node == child_timer)
422 timers_[actual_node].resume();
430 timers_[actual_node].stop(
false);
431 actual_node = timers_[actual_node].parent_timer;
434 if (actual_node == child_timer)
438 timers_[actual_node].resume();
443 void Profiler::stop_timer(
int timer_index) {
447 if (timers_[timer_index].running()) {
448 ASSERT_EQ(timer_index, (
int)actual_node).error();
449 stop_timer(*timers_[timer_index].code_point_);
456 void Profiler::add_calls(
unsigned int n_calls) {
457 timers_[actual_node].call_count += n_calls-1;
463 if (!global_monitor_memory)
466 MemoryAlloc::malloc_map()[p] =
static_cast<int>(size);
467 timers_[actual_node].total_allocated_ += size;
468 timers_[actual_node].current_allocated_ += size;
469 timers_[actual_node].alloc_called++;
471 if (timers_[actual_node].current_allocated_ > timers_[actual_node].max_allocated_)
472 timers_[actual_node].max_allocated_ = timers_[actual_node].current_allocated_;
478 if (!global_monitor_memory)
481 int size =
sizeof(p);
482 if (MemoryAlloc::malloc_map()[(long)p] > 0) {
483 size = MemoryAlloc::malloc_map()[(long)p];
484 MemoryAlloc::malloc_map().erase((
long)p);
486 timers_[actual_node].total_deallocated_ += size;
487 timers_[actual_node].current_allocated_ -= size;
488 timers_[actual_node].dealloc_called++;
493 const int measurements = 100;
497 for (
unsigned int i = 1; i < measurements; i++) {
502 while ((t2 - t1) == 0) t2 =
TimePoint ();
508 return (result / measurements) * 1000;
512 std::string common_prefix( std::string a, std::string b ) {
513 if( a.size() > b.size() )
std::swap(a,b) ;
514 return std::string( a.begin(), std::mismatch( a.begin(), a.end(), b.begin() ).first ) ;
519 template<
typename ReduceFunctor>
520 void Profiler::add_timer_info(ReduceFunctor reduce,
nlohmann::json* holder,
int timer_idx,
double parent_time) {
523 Timer &timer = timers_[timer_idx];
524 ASSERT(timer_idx >=0)(timer_idx).error(
"Wrong timer index.");
525 ASSERT(timer.parent_timer >=0).error(
"Inconsistent tree.");
528 string filepath = timer.code_point_->file_;
531 #ifdef FLOW123D_SOURCE_DIR 532 string common_path = common_prefix (
string(FLOW123D_SOURCE_DIR), filepath);
533 filepath.erase (0, common_path.size());
540 double cumul_time_sum;
541 node[
"tag"] = timer.tag();
542 node[
"file-path"] = filepath;
543 node[
"file-line"] = timer.code_point_->line_;
544 node[
"function"] = timer.code_point_->func_;
545 cumul_time_sum = reduce(timer, node);
549 if (timer_idx == 0) parent_time = cumul_time_sum;
550 double percent = parent_time > 1.0e-10 ? cumul_time_sum / parent_time * 100.0 : 0.0;
551 node[
"percent"] = percent;
555 bool has_children =
false;
556 for (
unsigned int i = 0; i < Timer::max_n_childs; i++) {
557 if (timer.child_timers[i] != timer_no_child) {
558 add_timer_info (reduce, &children, timer.child_timers[i], cumul_time_sum);
568 node[
"children"] = children;
577 void save_nonmpi_metric (
nlohmann::json &node, T * ptr,
string name) {
578 node[name +
"-min"] = *ptr;
579 node[name +
"-max"] = *ptr;
580 node[name +
"-sum"] = *ptr;
583 std::shared_ptr<std::ostream> Profiler::get_default_output_stream() {
587 return make_shared<ofstream>(json_filepath.c_str());
591 #ifdef FLOW123D_HAVE_MPI 600 int mpi_rank, mpi_size;
607 bool temp_memory_monitoring = global_monitor_memory;
608 set_memory_monitoring(
false, petsc_monitor_memory);
620 int call_count = timer.call_count;
621 double cumul_time = timer.cumulative_time ();
623 long memory_allocated = (long)timer.total_allocated_;
624 long memory_deallocated = (
long)timer.total_deallocated_;
625 long memory_peak = (long)timer.max_allocated_;
627 int alloc_called = timer.alloc_called;
628 int dealloc_called = timer.dealloc_called;
631 save_mpi_metric<double>(node, comm, &cumul_time,
"cumul-time");
632 save_mpi_metric<int>(node, comm, &call_count,
"call-count");
634 save_mpi_metric<long>(node, comm, &memory_allocated,
"memory-alloc");
635 save_mpi_metric<long>(node, comm, &memory_deallocated,
"memory-dealloc");
636 save_mpi_metric<long>(node, comm, &memory_peak,
"memory-peak");
638 save_mpi_metric<int>(node, comm, &alloc_called,
"memory-alloc-called");
639 save_mpi_metric<int>(node, comm, &dealloc_called,
"memory-dealloc-called");
641 #ifdef FLOW123D_HAVE_PETSC 642 long petsc_memory_difference = (long)timer.petsc_memory_difference;
643 long petsc_peak_memory = (
long)timer.petsc_peak_memory;
644 save_mpi_metric<long>(node, comm, &petsc_memory_difference,
"memory-petsc-diff");
645 save_mpi_metric<long>(node, comm, &petsc_peak_memory,
"memory-petsc-peak");
646 #endif // FLOW123D_HAVE_PETSC 651 add_timer_info (reduce, &jsonChildren, 0, 0.0);
652 jsonRoot[
"children"] = jsonChildren;
653 output_header(jsonRoot, mpi_size);
664 const int FLOW123D_JSON_HUMAN_READABLE = 2;
666 os << jsonRoot.
dump(FLOW123D_JSON_HUMAN_READABLE) << endl;
668 }
catch (exception & e) {
670 ss <<
"nlohmann::json::dump error: " << e.what() <<
"\n";
671 THROW( ExcMessage() << EI_Message(ss.str()) );
675 set_memory_monitoring(temp_memory_monitoring, petsc_monitor_memory);
684 if (profiler_path ==
"") {
685 output(comm, *get_default_output_stream());
687 json_filepath = profiler_path;
688 std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
710 const int FLOW123D_MPI_SINGLE_PROCESS = 1;
711 output_header(jsonRoot, FLOW123D_MPI_SINGLE_PROCESS);
718 int call_count = timer.call_count;
719 double cumul_time = timer.cumulative_time ();
721 long memory_allocated = (long)timer.total_allocated_;
722 long memory_deallocated = (
long)timer.total_deallocated_;
723 long memory_peak = (long)timer.max_allocated_;
725 int alloc_called = timer.alloc_called;
726 int dealloc_called = timer.dealloc_called;
728 save_nonmpi_metric<double>(node, &cumul_time,
"cumul-time");
729 save_nonmpi_metric<int>(node, &call_count,
"call-count");
731 save_nonmpi_metric<long>(node, &memory_allocated,
"memory-alloc");
732 save_nonmpi_metric<long>(node, &memory_deallocated,
"memory-dealloc");
733 save_nonmpi_metric<long>(node, &memory_peak,
"memory-peak");
735 save_nonmpi_metric<int>(node, &alloc_called,
"memory-alloc-called");
736 save_nonmpi_metric<int>(node, &dealloc_called,
"memory-dealloc-called");
738 #ifdef FLOW123D_HAVE_PETSC 739 long petsc_memory_difference = (long)timer.petsc_memory_difference;
740 long petsc_peak_memory = (
long)timer.petsc_peak_memory;
741 save_nonmpi_metric<long>(node, &petsc_memory_difference,
"memory-petsc-diff");
742 save_nonmpi_metric<long>(node, &petsc_peak_memory,
"memory-petsc-peak");
743 #endif // FLOW123D_HAVE_PETSC 748 add_timer_info(reduce, &jsonChildren, 0, 0.0);
749 jsonRoot[
"children"] = jsonChildren;
756 const int FLOW123D_JSON_HUMAN_READABLE = 2;
758 os << jsonRoot.
dump(FLOW123D_JSON_HUMAN_READABLE) << endl;
760 }
catch (exception & e) {
762 ss <<
"nlohmann::json::dump error: " << e.what() <<
"\n";
763 THROW( ExcMessage() << EI_Message(ss.str()) );
769 if(profiler_path ==
"") {
770 output(*get_default_output_stream());
772 json_filepath = profiler_path;
773 std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
778 void Profiler::output_header (
nlohmann::json &root,
int mpi_size) {
779 time_t end_time = time(NULL);
781 const char format[] =
"%x %X";
782 char start_time_string[BUFSIZ] = {0};
783 strftime(start_time_string,
sizeof (start_time_string) - 1, format, localtime(&start_time));
785 char end_time_string[BUFSIZ] = {0};
786 strftime(end_time_string,
sizeof (end_time_string) - 1, format, localtime(&end_time));
789 root[
"program-name"] = flow_name_;
790 root[
"program-version"] = flow_version_;
791 root[
"program-branch"] = flow_branch_;
792 root[
"program-revision"] = flow_revision_;
793 root[
"program-build"] = flow_build_;
797 root[
"task-description"] = task_description_;
798 root[
"task-size"] = task_size_;
801 root[
"run-process-count"] = mpi_size;
802 root[
"run-started-at"] = start_time_string;
803 root[
"run-finished-at"] = end_time_string;
806 #ifdef FLOW123D_HAVE_PYTHON 809 if (json_filepath ==
"")
return;
818 #ifndef FLOW123D_HAVE_CYGWIN 820 PyObject * python_module = PythonLoader::load_module_by_name (
"profiler.profiler_formatter_module");
824 PyObject * convert_method = PythonLoader::get_callable (python_module,
"convert" );
826 int argument_index = 0;
827 PyObject * arguments = PyTuple_New (3);
830 PyObject * tmp = PyUnicode_FromString (json_filepath.c_str());
831 PyTuple_SetItem (arguments, argument_index++, tmp);
834 tmp = PyUnicode_FromString ((json_filepath + output_file_suffix).c_str());
835 PyTuple_SetItem (arguments, argument_index++, tmp);
838 tmp = PyUnicode_FromString (formatter.c_str());
839 PyTuple_SetItem (arguments, argument_index++, tmp);
842 PyObject_CallObject (convert_method, arguments);
844 PythonLoader::check_error();
849 MessageOut() <<
"# Note: converting json profiler reports is not" 850 <<
" supported under Windows or Cygwin environment for now.\n" 851 <<
"# You can use python script located in bin/python folder" 852 <<
" in order to convert json report to txt or csv format.\n" 853 <<
"python profiler_formatter_script.py --input \"" << json_filepath
854 <<
"\" --output \"profiler.txt\"" << std::endl;
855 #endif // FLOW123D_HAVE_CYGWIN 861 #endif // FLOW123D_HAVE_PYTHON 867 .error(
"Forbidden to uninitialize the Profiler when actual timer is not zero.");
869 set_memory_monitoring(
false,
false);
873 bool Profiler::global_monitor_memory =
false;
874 bool Profiler::petsc_monitor_memory =
true;
875 void Profiler::set_memory_monitoring(
const bool global_monitor,
const bool petsc_monitor) {
876 global_monitor_memory = global_monitor;
877 petsc_monitor_memory = petsc_monitor;
880 bool Profiler::get_global_memory_monitoring() {
881 return global_monitor_memory;
884 bool Profiler::get_petsc_memory_monitoring() {
885 return petsc_monitor_memory;
888 unordered_map_with_alloc & MemoryAlloc::malloc_map() {
889 static unordered_map_with_alloc static_malloc_map;
890 return static_malloc_map;
893 void * Profiler::operator
new (
size_t size) {
894 return malloc (size);
897 void Profiler::operator
delete (
void* p) {
902 void * p = malloc(size);
908 void * p = malloc(size);
913 void *
operator new[] (std::size_t size,
const std::nothrow_t&)
throw() {
914 void * p = malloc(size);
919 void operator delete(
void *p)
throw() {
924 void operator delete(
void *p, std::size_t)
throw() {
929 void operator delete[](
void *p)
throw() {
934 void operator delete[](
void *p, std::size_t)
throw() {
939 #else // def FLOW123D_DEBUG_PROFILER 957 .error(
"Forbidden to uninitialize the Profiler when actual timer is not zero.");
958 set_memory_monitoring(
false,
false);
966 #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
#define WarningOut()
Macro defining 'warning' record of log.
static Profiler * instance(bool clear=false)
#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)