Flow123d  release_3.0.0-1191-g7740876
sys_profiler.cc
Go to the documentation of this file.
1 /*!
2  *
3  * Copyright (C) 2015 Technical University of Liberec. All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify it under
6  * the terms of the GNU General Public License version 3 as published by the
7  * Free Software Foundation. (http://www.gnu.org/licenses/gpl-3.0.en.html)
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12  *
13  *
14  * @file sys_profiler.cc
15  * @ingroup system
16  * @brief Profiler
17  */
18 
19 
20 // Fat header
21 
22 #include <fstream>
23 #include <iomanip>
24 #include <sys/param.h>
25 
26 #ifdef FLOW123D_HAVE_PYTHON
27  #include "Python.h"
28 #endif // FLOW123D_HAVE_PYTHON
29 
30 #include "sys_profiler.hh"
31 #include "system/system.hh"
32 #include "system/python_loader.hh"
33 #include <iostream>
34 #include <boost/format.hpp>
35 #include <boost/unordered_map.hpp>
36 
37 #include "system/file_path.hh"
38 #include "system/python_loader.hh"
39 #include "mpi.h"
40 #include "time_point.hh"
41 
42 /*
43  * These should be replaced by using boost MPI interface
44  */
45 int MPI_Functions::sum(int* val, MPI_Comm comm) {
46  int total = 0;
47  MPI_Reduce(val, &total, 1, MPI_INT, MPI_SUM, 0, comm);
48  return total;
49  }
50 
51 double MPI_Functions::sum(double* val, MPI_Comm comm) {
52  double total = 0;
53  MPI_Reduce(val, &total, 1, MPI_DOUBLE, MPI_SUM, 0, comm);
54  return total;
55  }
56 
57 long MPI_Functions::sum(long* val, MPI_Comm comm) {
58  long total = 0;
59  MPI_Reduce(val, &total, 1, MPI_LONG, MPI_SUM, 0, comm);
60  return total;
61  }
62 
63 int MPI_Functions::min(int* val, MPI_Comm comm) {
64  int min = 0;
65  MPI_Reduce(val, &min, 1, MPI_INT, MPI_MIN, 0, comm);
66  return min;
67  }
68 
69 double MPI_Functions::min(double* val, MPI_Comm comm) {
70  double min = 0;
71  MPI_Reduce(val, &min, 1, MPI_DOUBLE, MPI_MIN, 0, comm);
72  return min;
73  }
74 
75 long MPI_Functions::min(long* val, MPI_Comm comm) {
76  long min = 0;
77  MPI_Reduce(val, &min, 1, MPI_LONG, MPI_MIN, 0, comm);
78  return min;
79  }
80 
81 int MPI_Functions::max(int* val, MPI_Comm comm) {
82  int max = 0;
83  MPI_Reduce(val, &max, 1, MPI_INT, MPI_MAX, 0, comm);
84  return max;
85  }
86 
87 double MPI_Functions::max(double* val, MPI_Comm comm) {
88  double max = 0;
89  MPI_Reduce(val, &max, 1, MPI_DOUBLE, MPI_MAX, 0, comm);
90  return max;
91  }
92 
93 long MPI_Functions::max(long* val, MPI_Comm comm) {
94  long max = 0;
95  MPI_Reduce(val, &max, 1, MPI_LONG, MPI_MAX, 0, comm);
96  return max;
97  }
98 
99 
100 #ifdef FLOW123D_DEBUG_PROFILER
101 /*********************************************************************************************
102  * Implementation of class Timer
103  */
104 
105 const int timer_no_child=-1;
106 
107 Timer::Timer(const CodePoint &cp, int parent)
108 : start_time(TimePoint()),
109  cumul_time(0.0),
110  call_count(0),
111  start_count(0),
112  code_point_(&cp),
113  full_hash_(cp.hash_),
114  hash_idx_(cp.hash_idx_),
115  parent_timer(parent),
116  total_allocated_(0),
117  total_deallocated_(0),
118  max_allocated_(0),
119  current_allocated_(0),
120  alloc_called(0),
121  dealloc_called(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
129 {
130  for(unsigned int i=0; i< max_n_childs ;i++) child_timers[i]=timer_no_child;
131 }
132 
133 
134 /**
135  * Debug information of the timer
136  */
137 ostream & operator <<(ostream& os, const Timer& timer) {
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
147  os << endl;
148  return os;
149 }
150 
151 
152 double Timer::cumulative_time() const {
153  return cumul_time;
154 }
155 
156 void Profiler::accept_from_child(Timer &parent, Timer &child) {
157  int child_timer = 0;
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) {
161  // propagate metrics from child to parent
162  accept_from_child(child, timers_[child_timer]);
163  }
164  }
165  // compute totals by adding values from child
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;
170 
171 #ifdef FLOW123D_HAVE_PETSC
172  if (petsc_monitor_memory) {
173  // add differences from child
174  parent.petsc_memory_difference += child.petsc_memory_difference;
175  parent.current_allocated_ += child.current_allocated_;
176 
177  // when computing maximum, we take greater value from parent and child
178  // PetscMemoryGetCurrentUsage always return absolute (not relative) value
179  parent.petsc_peak_memory = max(parent.petsc_peak_memory, child.petsc_peak_memory);
180  }
181 #endif // FLOW123D_HAVE_PETSC
182 
183  parent.max_allocated_ = max(parent.max_allocated_, child.max_allocated_);
184 }
185 
186 
187 void Timer::pause() {
188 #ifdef FLOW123D_HAVE_PETSC
189  if (Profiler::get_petsc_memory_monitoring()) {
190  // get the maximum resident set size (memory used) for the program.
191  PetscMemoryGetMaximumUsage(&petsc_local_peak_memory);
192  if (petsc_peak_memory < petsc_local_peak_memory)
193  petsc_peak_memory = petsc_local_peak_memory;
194  }
195 #endif // FLOW123D_HAVE_PETSC
196 }
197 
198 void Timer::resume() {
199 #ifdef FLOW123D_HAVE_PETSC
200  if (Profiler::get_petsc_memory_monitoring()) {
201  // tell PETSc to monitor the maximum memory usage so
202  // that PetscMemoryGetMaximumUsage() will work.
203  PetscMemorySetGetMaximumUsage();
204  }
205 #endif // FLOW123D_HAVE_PETSC
206 }
207 
208 void Timer::start() {
209 #ifdef FLOW123D_HAVE_PETSC
210  if (Profiler::get_petsc_memory_monitoring()) {
211  // Tell PETSc to monitor the maximum memory usage so
212  // that PetscMemoryGetMaximumUsage() will work.
213  PetscMemorySetGetMaximumUsage();
214  PetscMemoryGetCurrentUsage (&petsc_start_memory);
215  }
216 #endif // FLOW123D_HAVE_PETSC
217 
218  if (start_count == 0) {
219  start_time = TimePoint();
220  }
221  call_count++;
222  start_count++;
223 }
224 
225 
226 
227 bool Timer::stop(bool forced) {
228 #ifdef FLOW123D_HAVE_PETSC
229  if (Profiler::get_petsc_memory_monitoring()) {
230  // get current memory usage
231  PetscMemoryGetCurrentUsage (&petsc_end_memory);
232  petsc_memory_difference += petsc_end_memory - petsc_start_memory;
233 
234  // get the maximum resident set size (memory used) for the program.
235  PetscMemoryGetMaximumUsage(&petsc_local_peak_memory);
236  if (petsc_peak_memory < petsc_local_peak_memory)
237  petsc_peak_memory = petsc_local_peak_memory;
238  }
239 #endif // FLOW123D_HAVE_PETSC
240 
241  if (forced) start_count=1;
242 
243  if (start_count == 1) {
244  cumul_time += (TimePoint() - start_time);
245  start_count--;
246  return true;
247  } else {
248  start_count--;
249  }
250  return false;
251 }
252 
253 
254 
255 void Timer::add_child(int child_index, const Timer &child)
256 {
257  unsigned int idx = child.hash_idx_;
258  if (child_timers[idx] != timer_no_child) {
259  // hash collision, find first empty place
260  unsigned int i=idx;
261  do {
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");
265  idx=i;
266  }
267  //DebugOut().fmt("Adding child {} at index: {}\n", child_index, idx);
268  child_timers[idx] = child_index;
269 }
270 
271 
272 
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_ );
275 }
276 
277 
278 /***********************************************************************************************
279  * Implementation of Profiler
280  */
281 
282 
284  if (_instance == NULL) {
285  MemoryAlloc::malloc_map().reserve(Profiler::malloc_map_reserve);
286  _instance = new Profiler();
287  }
288  return _instance;
289  }
290 
291 
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);
296 
297 void Profiler::initialize() {
298  instance();
299  set_memory_monitoring(true, true);
300 }
301 
302 
304 : actual_node(0),
305  task_size_(1),
306  start_time( time(NULL) ),
307  json_filepath("")
308 
309 {
310 #ifdef FLOW123D_DEBUG_PROFILER
311  timers_.push_back( Timer(main_cp, 0) );
312  timers_[0].start();
313 #endif
314 }
315 
316 
317 
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) {
322  // propagate metrics from child to Whole-Program time-frame
323  accept_from_child(timers_[0], timers_[child_timer]);
324  }
325  }
326 }
327 
328 
329 
330 void Profiler::set_task_info(string description, int size) {
331  task_description_ = description;
332  task_size_ = size;
333 }
334 
335 
336 
337 void Profiler::set_program_info(string program_name, string program_version, string branch, string revision, string build) {
338  flow_name_ = program_name;
339  flow_version_ = program_version;
340  flow_branch_ = branch;
341  flow_revision_ = revision;
342  flow_build_ = build;
343 }
344 
345 
346 
347 int Profiler::start_timer(const CodePoint &cp) {
348  unsigned int parent_node = actual_node;
349  //DebugOut().fmt("Start timer: {}\n", cp.tag_);
350  int child_idx = find_child(cp);
351  if (child_idx < 0) {
352  //DebugOut().fmt("Adding timer: {}\n", cp.tag_);
353  // tag not present - create new timer
354  child_idx=timers_.size();
355  timers_.push_back( Timer(cp, actual_node) );
356  timers_[actual_node].add_child(child_idx , timers_.back() );
357  }
358  actual_node=child_idx;
359 
360  // pause current timer
361  timers_[parent_node].pause();
362 
363  timers_[actual_node].start();
364 
365  return actual_node;
366 }
367 
368 
369 
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;
374  do {
375  if (timer.child_timers[idx] == timer_no_child) break; // tag is not there
376 
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_ ); // passed through whole array
382  return -1;
383 }
384 
385 
386 
387 void Profiler::stop_timer(const CodePoint &cp) {
388 #ifdef FLOW123D_DEBUG
389  // check that all childrens are closed
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.");
395 #endif
396  unsigned int child_timer = actual_node;
397  if ( cp.hash_ != timers_[actual_node].full_hash_) {
398  // timer to close is not actual - we search for it above actual
399  for(unsigned int node=actual_node; node != 0; node=timers_[node].parent_timer) {
400  if ( cp.hash_ == timers_[node].full_hash_) {
401  // found above - close all nodes between
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);
406  }
407  // close 'node' itself
408  timers_[actual_node].stop(false);
409  actual_node = timers_[actual_node].parent_timer;
410 
411  // actual_node == child_timer indicates this is root
412  if (actual_node == child_timer)
413  return;
414 
415  // resume current timer
416  timers_[actual_node].resume();
417  return;
418  }
419  }
420  // node not found - do nothing
421  return;
422  }
423  // node to close match the actual
424  timers_[actual_node].stop(false);
425  actual_node = timers_[actual_node].parent_timer;
426 
427  // actual_node == child_timer indicates this is root
428  if (actual_node == child_timer)
429  return;
430 
431  // resume current timer
432  timers_[actual_node].resume();
433 }
434 
435 
436 
437 void Profiler::stop_timer(int timer_index) {
438  // stop_timer with CodePoint type
439  // timer which is still running MUST be the same as actual_node index
440  // if timer is not running index will differ
441  if (timers_[timer_index].running()) {
442  ASSERT_EQ(timer_index, (int)actual_node).error();
443  stop_timer(*timers_[timer_index].code_point_);
444  }
445 
446 }
447 
448 
449 
450 void Profiler::add_calls(unsigned int n_calls) {
451  timers_[actual_node].call_count += n_calls-1;
452 }
453 
454 
455 
456 void Profiler::notify_malloc(const size_t size, const long p) {
457  if (!global_monitor_memory)
458  return;
459 
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++;
464 
465  if (timers_[actual_node].current_allocated_ > timers_[actual_node].max_allocated_)
466  timers_[actual_node].max_allocated_ = timers_[actual_node].current_allocated_;
467 }
468 
469 
470 
471 void Profiler::notify_free(const long p) {
472  if (!global_monitor_memory)
473  return;
474 
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);
479  }
480  timers_[actual_node].total_deallocated_ += size;
481  timers_[actual_node].current_allocated_ -= size;
482  timers_[actual_node].dealloc_called++;
483 }
484 
485 
486 double Profiler::get_resolution () {
487  const int measurements = 100;
488  double result = 0;
489 
490  // perform 100 measurements
491  for (unsigned int i = 1; i < measurements; i++) {
492  TimePoint t1 = TimePoint ();
493  TimePoint t2 = TimePoint ();
494 
495  // double comparison should be avoided
496  while ((t2 - t1) == 0) t2 = TimePoint ();
497  // while ((t2.ticks - t1.ticks) == 0) t2 = TimePoint ();
498 
499  result += t2 - t1;
500  }
501 
502  return (result / measurements) * 1000; // ticks to seconds to microseconds conversion
503 }
504 
505 
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 ) ;
509 }
510 
511 
512 
513 template<typename ReduceFunctor>
514 void Profiler::add_timer_info(ReduceFunctor reduce, nlohmann::json* holder, int timer_idx, double parent_time) {
515 
516  // get timer and check preconditions
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.");
520 
521  // fix path
522  string filepath = timer.code_point_->file_;
523 
524  // if constant FLOW123D_SOURCE_DIR is defined, we try to erase it from beginning of each CodePoint's filepath
525  #ifdef FLOW123D_SOURCE_DIR
526  string common_path = common_prefix (string(FLOW123D_SOURCE_DIR), filepath);
527  filepath.erase (0, common_path.size());
528  #endif
529 
530 
531  // generate node representing this timer
532  // add basic information
533  nlohmann::json node;
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);
540 
541 
542  // statistical info
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;
546 
547  // write times children timers using secured child_timers array
548  nlohmann::json children;
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);
553  /*
554  if (child_timers[i] != timer_no_child) {
555  add_timer_info (reduce, &children, child_timers[i], cumul_time_sum); */
556  has_children = true;
557  }
558  }
559 
560  // add children tag and other info if present
561  if (has_children) {
562  node["children"] = children;
563  }
564 
565  // add to the array
566  holder->push_back(node);
567 }
568 
569 
570 template <class T>
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;
575 }
576 
577 std::shared_ptr<std::ostream> Profiler::get_default_output_stream() {
578  json_filepath = FilePath("profiler_info.log.json", FilePath::output_file);
579 
580  //LogOut() << "output into: " << json_filepath << std::endl;
581  return make_shared<ofstream>(json_filepath.c_str());
582 }
583 
584 
585 #ifdef FLOW123D_HAVE_MPI
586 template <class T>
587 void save_mpi_metric (nlohmann::json &node, MPI_Comm comm, T * ptr, string name) {
588  node[name + "-min"] = MPI_Functions::min(ptr, comm);
589  node[name + "-max"] = MPI_Functions::max(ptr, comm);
590  node[name + "-sum"] = MPI_Functions::sum(ptr, comm);
591 }
592 
593 void Profiler::output(MPI_Comm comm, ostream &os) {
594  int mpi_rank, mpi_size;
595  //wait until profiling on all processors is finished
596  MPI_Barrier(comm);
597  stop_timer(0);
598  propagate_timers();
599 
600  // stop monitoring memory
601  bool temp_memory_monitoring = global_monitor_memory;
602  set_memory_monitoring(false, petsc_monitor_memory);
603 
604  chkerr( MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank) );
605  MPI_Comm_size(comm, &mpi_size);
606 
607  // output header
608  nlohmann::json jsonRoot, jsonChildren;
609 
610  // recursively add all timers info
611  // define lambda function which reduces timer from multiple processors
612  // MPI implementation uses MPI call to reduce values
613  auto reduce = [=] (Timer &timer, nlohmann::json &node) -> double {
614  int call_count = timer.call_count;
615  double cumul_time = timer.cumulative_time ();
616 
617  long memory_allocated = (long)timer.total_allocated_;
618  long memory_deallocated = (long)timer.total_deallocated_;
619  long memory_peak = (long)timer.max_allocated_;
620 
621  int alloc_called = timer.alloc_called;
622  int dealloc_called = timer.dealloc_called;
623 
624 
625  save_mpi_metric<double>(node, comm, &cumul_time, "cumul-time");
626  save_mpi_metric<int>(node, comm, &call_count, "call-count");
627 
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");
631  //
632  save_mpi_metric<int>(node, comm, &alloc_called, "memory-alloc-called");
633  save_mpi_metric<int>(node, comm, &dealloc_called, "memory-dealloc-called");
634 
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
641 
642  return MPI_Functions::sum(&cumul_time, comm);
643  };
644 
645  add_timer_info (reduce, &jsonChildren, 0, 0.0);
646  jsonRoot["children"] = jsonChildren;
647  output_header(jsonRoot, mpi_size);
648 
649 
650  // create profiler output only once (on the first processor)
651  // only active communicator should be the one with mpi_rank 0
652  if (mpi_rank == 0) {
653  try {
654  /**
655  * indent size
656  * results in json human readable format (indents, newlines)
657  */
658  const int FLOW123D_JSON_HUMAN_READABLE = 2;
659  // write result to stream
660  os << jsonRoot.dump(FLOW123D_JSON_HUMAN_READABLE) << endl;
661 
662  } catch (exception & e) {
663  stringstream ss;
664  ss << "nlohmann::json::dump error: " << e.what() << "\n";
665  THROW( ExcMessage() << EI_Message(ss.str()) );
666  }
667  }
668  // restore memory monitoring
669  set_memory_monitoring(temp_memory_monitoring, petsc_monitor_memory);
670 }
671 
672 
673 void Profiler::output(MPI_Comm comm, string profiler_path /* = "" */) {
674  int mpi_rank;
675  chkerr(MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank));
676 
677  if (mpi_rank == 0) {
678  if (profiler_path == "") {
679  output(comm, *get_default_output_stream());
680  } else {
681  json_filepath = profiler_path;
682  std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
683  output(comm, *os);
684  }
685  } else {
686  ostringstream os;
687  output(comm, os);
688  }
689 }
690 
691 #endif /* FLOW123D_HAVE_MPI */
692 
693 void Profiler::output(ostream &os) {
694  // last update
695  stop_timer(0);
696  propagate_timers();
697 
698  // output header
699  nlohmann::json jsonRoot, jsonChildren;
700  /**
701  * Constant representing number of MPI processes
702  * where there is no MPI to work with (so 1 process)
703  */
704  const int FLOW123D_MPI_SINGLE_PROCESS = 1;
705  output_header(jsonRoot, FLOW123D_MPI_SINGLE_PROCESS);
706 
707 
708  // recursively add all timers info
709  // define lambda function which reduces timer from multiple processors
710  // non-MPI implementation is just dummy repetition of initial value
711  auto reduce = [=] (Timer &timer, nlohmann::json &node) -> double {
712  int call_count = timer.call_count;
713  double cumul_time = timer.cumulative_time ();
714 
715  long memory_allocated = (long)timer.total_allocated_;
716  long memory_deallocated = (long)timer.total_deallocated_;
717  long memory_peak = (long)timer.max_allocated_;
718 
719  int alloc_called = timer.alloc_called;
720  int dealloc_called = timer.dealloc_called;
721 
722  save_nonmpi_metric<double>(node, &cumul_time, "cumul-time");
723  save_nonmpi_metric<int>(node, &call_count, "call-count");
724 
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");
728 
729  save_nonmpi_metric<int>(node, &alloc_called, "memory-alloc-called");
730  save_nonmpi_metric<int>(node, &dealloc_called, "memory-dealloc-called");
731 
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
738 
739  return cumul_time;
740  };
741 
742  add_timer_info(reduce, &jsonChildren, 0, 0.0);
743  jsonRoot["children"] = jsonChildren;
744 
745  try {
746  /**
747  * indent size
748  * results in json human readable format (indents, newlines)
749  */
750  const int FLOW123D_JSON_HUMAN_READABLE = 2;
751  // write result to stream
752  os << jsonRoot.dump(FLOW123D_JSON_HUMAN_READABLE) << endl;
753 
754  } catch (exception & e) {
755  stringstream ss;
756  ss << "nlohmann::json::dump error: " << e.what() << "\n";
757  THROW( ExcMessage() << EI_Message(ss.str()) );
758  }
759 }
760 
761 
762 void Profiler::output(string profiler_path /* = "" */) {
763  if(profiler_path == "") {
764  output(*get_default_output_stream());
765  } else {
766  json_filepath = profiler_path;
767  std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
768  output(*os);
769  }
770 }
771 
772 void Profiler::output_header (nlohmann::json &root, int mpi_size) {
773  time_t end_time = time(NULL);
774 
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));
778 
779  char end_time_string[BUFSIZ] = {0};
780  strftime(end_time_string, sizeof (end_time_string) - 1, format, localtime(&end_time));
781 
782  // generate current run details
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_;
788  root["timer-resolution"] = Profiler::get_resolution();
789 
790  // print some information about the task at the beginning
791  root["task-description"] = task_description_;
792  root["task-size"] = task_size_;
793 
794  //print some information about the task at the beginning
795  root["run-process-count"] = mpi_size;
796  root["run-started-at"] = start_time_string;
797  root["run-finished-at"] = end_time_string;
798 }
799 
800 #ifdef FLOW123D_HAVE_PYTHON
801 void Profiler::transform_profiler_data (const string &output_file_suffix, const string &formatter) {
802 
803  if (json_filepath == "") return;
804 
805  // error under CYGWIN environment : more details in this repo
806  // https://github.com/x3mSpeedy/cygwin-python-issue
807  //
808  // For now we only support profiler report conversion in UNIX environment
809  // Windows users will have to use a python script located in bin folder
810  //
811 
812  #ifndef FLOW123D_HAVE_CYGWIN
813  // grab module and function by importing module profiler_formatter_module.py
814  PyObject * python_module = PythonLoader::load_module_by_name ("profiler.profiler_formatter_module");
815  //
816  // def convert (json_location, output_file, formatter):
817  //
818  PyObject * convert_method = PythonLoader::get_callable (python_module, "convert" );
819 
820  int argument_index = 0;
821  PyObject * arguments = PyTuple_New (3);
822 
823  // set json path location as first argument
824  PyObject * tmp = PyUnicode_FromString (json_filepath.c_str());
825  PyTuple_SetItem (arguments, argument_index++, tmp);
826 
827  // set output path location as second argument
828  tmp = PyUnicode_FromString ((json_filepath + output_file_suffix).c_str());
829  PyTuple_SetItem (arguments, argument_index++, tmp);
830 
831  // set Formatter class as third value
832  tmp = PyUnicode_FromString (formatter.c_str());
833  PyTuple_SetItem (arguments, argument_index++, tmp);
834 
835  // execute method with arguments
836  PyObject_CallObject (convert_method, arguments);
837 
838  PythonLoader::check_error();
839 
840  #else
841 
842  // print information about windows-cygwin issue and offer manual solution
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
850 }
851 #else
852 void Profiler::transform_profiler_data (const string &output_file_suffix, const string &formatter) {
853 }
854 
855 #endif // FLOW123D_HAVE_PYTHON
856 
857 
858 void Profiler::uninitialize() {
859  if (_instance) {
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);
864  delete _instance;
865  _instance = NULL;
866  }
867 }
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;
873 }
874 
875 bool Profiler::get_global_memory_monitoring() {
876  return global_monitor_memory;
877 }
878 
879 bool Profiler::get_petsc_memory_monitoring() {
880  return petsc_monitor_memory;
881 }
882 
883 unordered_map_with_alloc & MemoryAlloc::malloc_map() {
884  static unordered_map_with_alloc static_malloc_map;
885  return static_malloc_map;
886 }
887 
888 void * Profiler::operator new (size_t size) {
889  return malloc (size);
890 }
891 
892 void Profiler::operator delete (void* p) {
893  free(p);
894 }
895 
896 void *operator new (std::size_t size) OPERATOR_NEW_THROW_EXCEPTION {
897  void * p = malloc(size);
898  Profiler::instance()->notify_malloc(size, (long)p);
899  return p;
900 }
901 
902 void *operator new[] (std::size_t size) OPERATOR_NEW_THROW_EXCEPTION {
903  void * p = malloc(size);
904  Profiler::instance()->notify_malloc(size, (long)p);
905  return p;
906 }
907 
908 void *operator new[] (std::size_t size, const std::nothrow_t&) throw() {
909  void * p = malloc(size);
910  Profiler::instance()->notify_malloc(size, (long)p);
911  return p;
912 }
913 
914 void operator delete( void *p) throw() {
915  Profiler::instance()->notify_free((long)p);
916  free(p);
917 }
918 
919 void operator delete[]( void *p) throw() {
920  Profiler::instance()->notify_free((long)p);
921  free(p);
922 }
923 
924 #else // def FLOW123D_DEBUG_PROFILER
925 
927  initialize();
928  return _instance;
929  }
930 
931 Profiler* Profiler::_instance = NULL;
932 
934  if (_instance == NULL) {
935  _instance = new Profiler();
936  set_memory_monitoring(true, true);
937  }
938 }
939 
941  if (_instance) {
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);
946  delete _instance;
947  _instance = NULL;
948  }
949 }
950 
951 
952 #endif // def FLOW123D_DEBUG_PROFILER
#define MPI_LONG
Definition: mpi.h:161
static int min(int *val, MPI_Comm comm)
Definition: sys_profiler.cc:63
#define CONSTEXPR_
Definition: sys_profiler.hh:84
int MPI_Comm
Definition: mpi.h:141
#define OPERATOR_NEW_THROW_EXCEPTION
Definition: system.hh:53
static int sum(int *val, MPI_Comm comm)
Definition: sys_profiler.cc:45
a class to store JSON values
Definition: json.hpp:173
#define MessageOut()
Macro defining &#39;message&#39; record of log.
Definition: logger.hh:243
double get_resolution() const
std::string format(CStringRef format_str, ArgList args)
Definition: format.h:3141
#define MPI_SUM
Definition: mpi.h:196
void chkerr(unsigned int ierr)
Replacement of new/delete operator in the spirit of xmalloc.
Definition: system.hh:147
#define ASSERT(expr)
Allow use shorter versions of macro names if these names is not used with external library...
Definition: asserts.hh:346
void notify_free(const size_t size)
#define MPI_Reduce(sendbuf, recvbuf, count, datatype, op, root, comm)
Definition: mpi.h:608
static void uninitialize()
#define MPI_MIN
Definition: mpi.h:198
static int max(int *val, MPI_Comm comm)
Definition: sys_profiler.cc:81
void set_program_info(string program_name, string program_version, string branch, string revision, string build)
void start()
Definition: memory.cc:39
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
Definition: json.hpp:8688
#define MPI_Comm_size
Definition: mpi.h:235
#define MPI_DOUBLE
Definition: mpi.h:156
STREAM & operator<<(STREAM &s, UpdateFlags u)
void push_back(basic_json &&val)
add an object to an array
Definition: json.hpp:4686
void transform_profiler_data(const string &output_file_suffix, const string &formatter)
#define MPI_Comm_rank
Definition: mpi.h:236
Dedicated class for storing path to input and output files.
Definition: file_path.hh:54
#define MPI_INT
Definition: mpi.h:160
static void initialize()
#define ASSERT_LT(a, b)
Definition of comparative assert macro (Less Than)
Definition: asserts.hh:295
string_t dump(const int indent=-1) const
serialization
Definition: json.hpp:2079
static Profiler * instance()
#define WarningOut()
Macro defining &#39;warning&#39; record of log.
Definition: logger.hh:246
#define MPI_COMM_WORLD
Definition: mpi.h:123
#define MPI_MAX
Definition: mpi.h:197
static Profiler * _instance
Definition: memory.cc:33
#define MPI_Barrier(comm)
Definition: mpi.h:531
void stop()
Definition: memory.cc:42
#define THROW(whole_exception_expr)
Wrapper for throw. Saves the throwing point.
Definition: exceptions.hh:53
void output(MPI_Comm comm, ostream &os)
#define ASSERT_EQ(a, b)
Definition of comparative assert macro (EQual)
Definition: asserts.hh:327
void set_task_info(string description, int size)
void notify_malloc(const size_t size)