Flow123d  release_3.0.0-1263-g7cf53c1
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  static Profiler * _instance = new Profiler();
285  return _instance;
286  }
287 
288 
289 // static CONSTEXPR_ CodePoint main_cp = CODE_POINT("Whole Program");
290 // Profiler* Profiler::_instance = NULL;
291 const long Profiler::malloc_map_reserve = 100 * 1000;
292 CodePoint Profiler::null_code_point = CodePoint("__no_tag__", "__no_file__", "__no_func__", 0);
293 
295 : actual_node(0),
296  task_size_(1),
297  start_time( time(NULL) ),
298  json_filepath("")
299 
300 {
301  static CONSTEXPR_ CodePoint main_cp = CODE_POINT("Whole Program");
302  set_memory_monitoring(true, true);
303 #ifdef FLOW123D_DEBUG_PROFILER
304  MemoryAlloc::malloc_map().reserve(Profiler::malloc_map_reserve);
305  timers_.push_back( Timer(main_cp, 0) );
306  timers_[0].start();
307 #endif
308 }
309 
310 
311 
312 void Profiler::propagate_timers() {
313  for (unsigned int i = 0; i < Timer::max_n_childs; i++) {
314  unsigned int child_timer = timers_[0].child_timers[i];
315  if ((signed int)child_timer != timer_no_child) {
316  // propagate metrics from child to Whole-Program time-frame
317  accept_from_child(timers_[0], timers_[child_timer]);
318  }
319  }
320 }
321 
322 
323 
324 void Profiler::set_task_info(string description, int size) {
325  task_description_ = description;
326  task_size_ = size;
327 }
328 
329 
330 
331 void Profiler::set_program_info(string program_name, string program_version, string branch, string revision, string build) {
332  flow_name_ = program_name;
333  flow_version_ = program_version;
334  flow_branch_ = branch;
335  flow_revision_ = revision;
336  flow_build_ = build;
337 }
338 
339 
340 
341 int Profiler::start_timer(const CodePoint &cp) {
342  unsigned int parent_node = actual_node;
343  //DebugOut().fmt("Start timer: {}\n", cp.tag_);
344  int child_idx = find_child(cp);
345  if (child_idx < 0) {
346  //DebugOut().fmt("Adding timer: {}\n", cp.tag_);
347  // tag not present - create new timer
348  child_idx=timers_.size();
349  timers_.push_back( Timer(cp, actual_node) );
350  timers_[actual_node].add_child(child_idx , timers_.back() );
351  }
352  actual_node=child_idx;
353 
354  // pause current timer
355  timers_[parent_node].pause();
356 
357  timers_[actual_node].start();
358 
359  return actual_node;
360 }
361 
362 
363 
364 int Profiler::find_child(const CodePoint &cp) {
365  Timer &timer =timers_[actual_node];
366  unsigned int idx = cp.hash_idx_;
367  unsigned int child_idx;
368  do {
369  if (timer.child_timers[idx] == timer_no_child) break; // tag is not there
370 
371  child_idx=timer.child_timers[idx];
372  ASSERT_LT(child_idx, timers_.size()).error();
373  if (timers_[child_idx].full_hash_ == cp.hash_) return child_idx;
374  idx = ( (unsigned int)(idx)==(Timer::max_n_childs - 1) ? 0 : idx+1 );
375  } while ( (unsigned int)(idx) != cp.hash_idx_ ); // passed through whole array
376  return -1;
377 }
378 
379 
380 
381 void Profiler::stop_timer(const CodePoint &cp) {
382 #ifdef FLOW123D_DEBUG
383  // check that all childrens are closed
384  Timer &timer=timers_[actual_node];
385  for(unsigned int i=0; i < Timer::max_n_childs; i++)
386  if (timer.child_timers[i] != timer_no_child)
387  ASSERT(! timers_[timer.child_timers[i]].running())(timers_[timer.child_timers[i]].tag())(timer.tag())
388  .error("Child timer running while closing timer.");
389 #endif
390  unsigned int child_timer = actual_node;
391  if ( cp.hash_ != timers_[actual_node].full_hash_) {
392  // timer to close is not actual - we search for it above actual
393  for(unsigned int node=actual_node; node != 0; node=timers_[node].parent_timer) {
394  if ( cp.hash_ == timers_[node].full_hash_) {
395  // found above - close all nodes between
396  for(; (unsigned int)(actual_node) != node; actual_node=timers_[actual_node].parent_timer) {
397  WarningOut() << "Timer to close '" << cp.tag_ << "' do not match actual timer '"
398  << timers_[actual_node].tag() << "'. Force closing actual." << std::endl;
399  timers_[actual_node].stop(true);
400  }
401  // close 'node' itself
402  timers_[actual_node].stop(false);
403  actual_node = timers_[actual_node].parent_timer;
404 
405  // actual_node == child_timer indicates this is root
406  if (actual_node == child_timer)
407  return;
408 
409  // resume current timer
410  timers_[actual_node].resume();
411  return;
412  }
413  }
414  // node not found - do nothing
415  return;
416  }
417  // node to close match the actual
418  timers_[actual_node].stop(false);
419  actual_node = timers_[actual_node].parent_timer;
420 
421  // actual_node == child_timer indicates this is root
422  if (actual_node == child_timer)
423  return;
424 
425  // resume current timer
426  timers_[actual_node].resume();
427 }
428 
429 
430 
431 void Profiler::stop_timer(int timer_index) {
432  // stop_timer with CodePoint type
433  // timer which is still running MUST be the same as actual_node index
434  // if timer is not running index will differ
435  if (timers_[timer_index].running()) {
436  ASSERT_EQ(timer_index, (int)actual_node).error();
437  stop_timer(*timers_[timer_index].code_point_);
438  }
439 
440 }
441 
442 
443 
444 void Profiler::add_calls(unsigned int n_calls) {
445  timers_[actual_node].call_count += n_calls-1;
446 }
447 
448 
449 
450 void Profiler::notify_malloc(const size_t size, const long p) {
451  if (!global_monitor_memory)
452  return;
453 
454  MemoryAlloc::malloc_map()[p] = static_cast<int>(size);
455  timers_[actual_node].total_allocated_ += size;
456  timers_[actual_node].current_allocated_ += size;
457  timers_[actual_node].alloc_called++;
458 
459  if (timers_[actual_node].current_allocated_ > timers_[actual_node].max_allocated_)
460  timers_[actual_node].max_allocated_ = timers_[actual_node].current_allocated_;
461 }
462 
463 
464 
465 void Profiler::notify_free(const long p) {
466  if (!global_monitor_memory)
467  return;
468 
469  int size = sizeof(p);
470  if (MemoryAlloc::malloc_map()[(long)p] > 0) {
471  size = MemoryAlloc::malloc_map()[(long)p];
472  MemoryAlloc::malloc_map().erase((long)p);
473  }
474  timers_[actual_node].total_deallocated_ += size;
475  timers_[actual_node].current_allocated_ -= size;
476  timers_[actual_node].dealloc_called++;
477 }
478 
479 
480 double Profiler::get_resolution () {
481  const int measurements = 100;
482  double result = 0;
483 
484  // perform 100 measurements
485  for (unsigned int i = 1; i < measurements; i++) {
486  TimePoint t1 = TimePoint ();
487  TimePoint t2 = TimePoint ();
488 
489  // double comparison should be avoided
490  while ((t2 - t1) == 0) t2 = TimePoint ();
491  // while ((t2.ticks - t1.ticks) == 0) t2 = TimePoint ();
492 
493  result += t2 - t1;
494  }
495 
496  return (result / measurements) * 1000; // ticks to seconds to microseconds conversion
497 }
498 
499 
500 std::string common_prefix( std::string a, std::string b ) {
501  if( a.size() > b.size() ) std::swap(a,b) ;
502  return std::string( a.begin(), std::mismatch( a.begin(), a.end(), b.begin() ).first ) ;
503 }
504 
505 
506 
507 template<typename ReduceFunctor>
508 void Profiler::add_timer_info(ReduceFunctor reduce, nlohmann::json* holder, int timer_idx, double parent_time) {
509 
510  // get timer and check preconditions
511  Timer &timer = timers_[timer_idx];
512  ASSERT(timer_idx >=0)(timer_idx).error("Wrong timer index.");
513  ASSERT(timer.parent_timer >=0).error("Inconsistent tree.");
514 
515  // fix path
516  string filepath = timer.code_point_->file_;
517 
518  // if constant FLOW123D_SOURCE_DIR is defined, we try to erase it from beginning of each CodePoint's filepath
519  #ifdef FLOW123D_SOURCE_DIR
520  string common_path = common_prefix (string(FLOW123D_SOURCE_DIR), filepath);
521  filepath.erase (0, common_path.size());
522  #endif
523 
524 
525  // generate node representing this timer
526  // add basic information
527  nlohmann::json node;
528  double cumul_time_sum;
529  node["tag"] = timer.tag();
530  node["file-path"] = filepath;
531  node["file-line"] = timer.code_point_->line_;
532  node["function"] = timer.code_point_->func_;
533  cumul_time_sum = reduce(timer, node);
534 
535 
536  // statistical info
537  if (timer_idx == 0) parent_time = cumul_time_sum;
538  double percent = parent_time > 1.0e-10 ? cumul_time_sum / parent_time * 100.0 : 0.0;
539  node["percent"] = percent;
540 
541  // write times children timers using secured child_timers array
542  nlohmann::json children;
543  bool has_children = false;
544  for (unsigned int i = 0; i < Timer::max_n_childs; i++) {
545  if (timer.child_timers[i] != timer_no_child) {
546  add_timer_info (reduce, &children, timer.child_timers[i], cumul_time_sum);
547  /*
548  if (child_timers[i] != timer_no_child) {
549  add_timer_info (reduce, &children, child_timers[i], cumul_time_sum); */
550  has_children = true;
551  }
552  }
553 
554  // add children tag and other info if present
555  if (has_children) {
556  node["children"] = children;
557  }
558 
559  // add to the array
560  holder->push_back(node);
561 }
562 
563 
564 template <class T>
565 void save_nonmpi_metric (nlohmann::json &node, T * ptr, string name) {
566  node[name + "-min"] = *ptr;
567  node[name + "-max"] = *ptr;
568  node[name + "-sum"] = *ptr;
569 }
570 
571 std::shared_ptr<std::ostream> Profiler::get_default_output_stream() {
572  json_filepath = FilePath("profiler_info.log.json", FilePath::output_file);
573 
574  //LogOut() << "output into: " << json_filepath << std::endl;
575  return make_shared<ofstream>(json_filepath.c_str());
576 }
577 
578 
579 #ifdef FLOW123D_HAVE_MPI
580 template <class T>
581 void save_mpi_metric (nlohmann::json &node, MPI_Comm comm, T * ptr, string name) {
582  node[name + "-min"] = MPI_Functions::min(ptr, comm);
583  node[name + "-max"] = MPI_Functions::max(ptr, comm);
584  node[name + "-sum"] = MPI_Functions::sum(ptr, comm);
585 }
586 
587 void Profiler::output(MPI_Comm comm, ostream &os) {
588  int mpi_rank, mpi_size;
589  //wait until profiling on all processors is finished
590  MPI_Barrier(comm);
591  stop_timer(0);
592  propagate_timers();
593 
594  // stop monitoring memory
595  bool temp_memory_monitoring = global_monitor_memory;
596  set_memory_monitoring(false, petsc_monitor_memory);
597 
598  chkerr( MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank) );
599  MPI_Comm_size(comm, &mpi_size);
600 
601  // output header
602  nlohmann::json jsonRoot, jsonChildren;
603 
604  // recursively add all timers info
605  // define lambda function which reduces timer from multiple processors
606  // MPI implementation uses MPI call to reduce values
607  auto reduce = [=] (Timer &timer, nlohmann::json &node) -> double {
608  int call_count = timer.call_count;
609  double cumul_time = timer.cumulative_time ();
610 
611  long memory_allocated = (long)timer.total_allocated_;
612  long memory_deallocated = (long)timer.total_deallocated_;
613  long memory_peak = (long)timer.max_allocated_;
614 
615  int alloc_called = timer.alloc_called;
616  int dealloc_called = timer.dealloc_called;
617 
618 
619  save_mpi_metric<double>(node, comm, &cumul_time, "cumul-time");
620  save_mpi_metric<int>(node, comm, &call_count, "call-count");
621 
622  save_mpi_metric<long>(node, comm, &memory_allocated, "memory-alloc");
623  save_mpi_metric<long>(node, comm, &memory_deallocated, "memory-dealloc");
624  save_mpi_metric<long>(node, comm, &memory_peak, "memory-peak");
625  //
626  save_mpi_metric<int>(node, comm, &alloc_called, "memory-alloc-called");
627  save_mpi_metric<int>(node, comm, &dealloc_called, "memory-dealloc-called");
628 
629 #ifdef FLOW123D_HAVE_PETSC
630  long petsc_memory_difference = (long)timer.petsc_memory_difference;
631  long petsc_peak_memory = (long)timer.petsc_peak_memory;
632  save_mpi_metric<long>(node, comm, &petsc_memory_difference, "memory-petsc-diff");
633  save_mpi_metric<long>(node, comm, &petsc_peak_memory, "memory-petsc-peak");
634 #endif // FLOW123D_HAVE_PETSC
635 
636  return MPI_Functions::sum(&cumul_time, comm);
637  };
638 
639  add_timer_info (reduce, &jsonChildren, 0, 0.0);
640  jsonRoot["children"] = jsonChildren;
641  output_header(jsonRoot, mpi_size);
642 
643 
644  // create profiler output only once (on the first processor)
645  // only active communicator should be the one with mpi_rank 0
646  if (mpi_rank == 0) {
647  try {
648  /**
649  * indent size
650  * results in json human readable format (indents, newlines)
651  */
652  const int FLOW123D_JSON_HUMAN_READABLE = 2;
653  // write result to stream
654  os << jsonRoot.dump(FLOW123D_JSON_HUMAN_READABLE) << endl;
655 
656  } catch (exception & e) {
657  stringstream ss;
658  ss << "nlohmann::json::dump error: " << e.what() << "\n";
659  THROW( ExcMessage() << EI_Message(ss.str()) );
660  }
661  }
662  // restore memory monitoring
663  set_memory_monitoring(temp_memory_monitoring, petsc_monitor_memory);
664 }
665 
666 
667 void Profiler::output(MPI_Comm comm, string profiler_path /* = "" */) {
668  int mpi_rank;
669  chkerr(MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank));
670 
671  if (mpi_rank == 0) {
672  if (profiler_path == "") {
673  output(comm, *get_default_output_stream());
674  } else {
675  json_filepath = profiler_path;
676  std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
677  output(comm, *os);
678  }
679  } else {
680  ostringstream os;
681  output(comm, os);
682  }
683 }
684 
685 #endif /* FLOW123D_HAVE_MPI */
686 
687 void Profiler::output(ostream &os) {
688  // last update
689  stop_timer(0);
690  propagate_timers();
691 
692  // output header
693  nlohmann::json jsonRoot, jsonChildren;
694  /**
695  * Constant representing number of MPI processes
696  * where there is no MPI to work with (so 1 process)
697  */
698  const int FLOW123D_MPI_SINGLE_PROCESS = 1;
699  output_header(jsonRoot, FLOW123D_MPI_SINGLE_PROCESS);
700 
701 
702  // recursively add all timers info
703  // define lambda function which reduces timer from multiple processors
704  // non-MPI implementation is just dummy repetition of initial value
705  auto reduce = [=] (Timer &timer, nlohmann::json &node) -> double {
706  int call_count = timer.call_count;
707  double cumul_time = timer.cumulative_time ();
708 
709  long memory_allocated = (long)timer.total_allocated_;
710  long memory_deallocated = (long)timer.total_deallocated_;
711  long memory_peak = (long)timer.max_allocated_;
712 
713  int alloc_called = timer.alloc_called;
714  int dealloc_called = timer.dealloc_called;
715 
716  save_nonmpi_metric<double>(node, &cumul_time, "cumul-time");
717  save_nonmpi_metric<int>(node, &call_count, "call-count");
718 
719  save_nonmpi_metric<long>(node, &memory_allocated, "memory-alloc");
720  save_nonmpi_metric<long>(node, &memory_deallocated, "memory-dealloc");
721  save_nonmpi_metric<long>(node, &memory_peak, "memory-peak");
722 
723  save_nonmpi_metric<int>(node, &alloc_called, "memory-alloc-called");
724  save_nonmpi_metric<int>(node, &dealloc_called, "memory-dealloc-called");
725 
726 #ifdef FLOW123D_HAVE_PETSC
727  long petsc_memory_difference = (long)timer.petsc_memory_difference;
728  long petsc_peak_memory = (long)timer.petsc_peak_memory;
729  save_nonmpi_metric<long>(node, &petsc_memory_difference, "memory-petsc-diff");
730  save_nonmpi_metric<long>(node, &petsc_peak_memory, "memory-petsc-peak");
731 #endif // FLOW123D_HAVE_PETSC
732 
733  return cumul_time;
734  };
735 
736  add_timer_info(reduce, &jsonChildren, 0, 0.0);
737  jsonRoot["children"] = jsonChildren;
738 
739  try {
740  /**
741  * indent size
742  * results in json human readable format (indents, newlines)
743  */
744  const int FLOW123D_JSON_HUMAN_READABLE = 2;
745  // write result to stream
746  os << jsonRoot.dump(FLOW123D_JSON_HUMAN_READABLE) << endl;
747 
748  } catch (exception & e) {
749  stringstream ss;
750  ss << "nlohmann::json::dump error: " << e.what() << "\n";
751  THROW( ExcMessage() << EI_Message(ss.str()) );
752  }
753 }
754 
755 
756 void Profiler::output(string profiler_path /* = "" */) {
757  if(profiler_path == "") {
758  output(*get_default_output_stream());
759  } else {
760  json_filepath = profiler_path;
761  std::shared_ptr<std::ostream> os = make_shared<ofstream>(profiler_path.c_str());
762  output(*os);
763  }
764 }
765 
766 void Profiler::output_header (nlohmann::json &root, int mpi_size) {
767  time_t end_time = time(NULL);
768 
769  const char format[] = "%x %X";
770  char start_time_string[BUFSIZ] = {0};
771  strftime(start_time_string, sizeof (start_time_string) - 1, format, localtime(&start_time));
772 
773  char end_time_string[BUFSIZ] = {0};
774  strftime(end_time_string, sizeof (end_time_string) - 1, format, localtime(&end_time));
775 
776  // generate current run details
777  root["program-name"] = flow_name_;
778  root["program-version"] = flow_version_;
779  root["program-branch"] = flow_branch_;
780  root["program-revision"] = flow_revision_;
781  root["program-build"] = flow_build_;
782  root["timer-resolution"] = Profiler::get_resolution();
783 
784  // print some information about the task at the beginning
785  root["task-description"] = task_description_;
786  root["task-size"] = task_size_;
787 
788  //print some information about the task at the beginning
789  root["run-process-count"] = mpi_size;
790  root["run-started-at"] = start_time_string;
791  root["run-finished-at"] = end_time_string;
792 }
793 
794 #ifdef FLOW123D_HAVE_PYTHON
795 void Profiler::transform_profiler_data (const string &output_file_suffix, const string &formatter) {
796 
797  if (json_filepath == "") return;
798 
799  // error under CYGWIN environment : more details in this repo
800  // https://github.com/x3mSpeedy/cygwin-python-issue
801  //
802  // For now we only support profiler report conversion in UNIX environment
803  // Windows users will have to use a python script located in bin folder
804  //
805 
806  #ifndef FLOW123D_HAVE_CYGWIN
807  // grab module and function by importing module profiler_formatter_module.py
808  PyObject * python_module = PythonLoader::load_module_by_name ("profiler.profiler_formatter_module");
809  //
810  // def convert (json_location, output_file, formatter):
811  //
812  PyObject * convert_method = PythonLoader::get_callable (python_module, "convert" );
813 
814  int argument_index = 0;
815  PyObject * arguments = PyTuple_New (3);
816 
817  // set json path location as first argument
818  PyObject * tmp = PyUnicode_FromString (json_filepath.c_str());
819  PyTuple_SetItem (arguments, argument_index++, tmp);
820 
821  // set output path location as second argument
822  tmp = PyUnicode_FromString ((json_filepath + output_file_suffix).c_str());
823  PyTuple_SetItem (arguments, argument_index++, tmp);
824 
825  // set Formatter class as third value
826  tmp = PyUnicode_FromString (formatter.c_str());
827  PyTuple_SetItem (arguments, argument_index++, tmp);
828 
829  // execute method with arguments
830  PyObject_CallObject (convert_method, arguments);
831 
832  PythonLoader::check_error();
833 
834  #else
835 
836  // print information about windows-cygwin issue and offer manual solution
837  MessageOut() << "# Note: converting json profiler reports is not"
838  << " supported under Windows or Cygwin environment for now.\n"
839  << "# You can use python script located in bin/python folder"
840  << " in order to convert json report to txt or csv format.\n"
841  << "python profiler_formatter_script.py --input \"" << json_filepath
842  << "\" --output \"profiler.txt\"" << std::endl;
843  #endif // FLOW123D_HAVE_CYGWIN
844 }
845 #else
846 void Profiler::transform_profiler_data (const string &output_file_suffix, const string &formatter) {
847 }
848 
849 #endif // FLOW123D_HAVE_PYTHON
850 
851 
852 void Profiler::uninitialize() {
853  if (Profiler::instance()) {
854  ASSERT(Profiler::instance()->actual_node==0)(Profiler::instance()->timers_[Profiler::instance()->actual_node].tag())
855  .error("Forbidden to uninitialize the Profiler when actual timer is not zero.");
856  Profiler::instance()->stop_timer(0);
857  set_memory_monitoring(false, false);
858  // delete _instance;
859  // _instance = NULL;
860  }
861 }
862 bool Profiler::global_monitor_memory = false;
863 bool Profiler::petsc_monitor_memory = true;
864 void Profiler::set_memory_monitoring(const bool global_monitor, const bool petsc_monitor) {
865  global_monitor_memory = global_monitor;
866  petsc_monitor_memory = petsc_monitor;
867 }
868 
869 bool Profiler::get_global_memory_monitoring() {
870  return global_monitor_memory;
871 }
872 
873 bool Profiler::get_petsc_memory_monitoring() {
874  return petsc_monitor_memory;
875 }
876 
877 unordered_map_with_alloc & MemoryAlloc::malloc_map() {
878  static unordered_map_with_alloc static_malloc_map;
879  return static_malloc_map;
880 }
881 
882 void * Profiler::operator new (size_t size) {
883  return malloc (size);
884 }
885 
886 void Profiler::operator delete (void* p) {
887  free(p);
888 }
889 
890 void *operator new (std::size_t size) OPERATOR_NEW_THROW_EXCEPTION {
891  void * p = malloc(size);
892  Profiler::instance()->notify_malloc(size, (long)p);
893  return 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, const std::nothrow_t&) throw() {
903  void * p = malloc(size);
904  Profiler::instance()->notify_malloc(size, (long)p);
905  return p;
906 }
907 
908 void operator delete( void *p) throw() {
909  Profiler::instance()->notify_free((long)p);
910  free(p);
911 }
912 
913 void operator delete[]( void *p) throw() {
914  Profiler::instance()->notify_free((long)p);
915  free(p);
916 }
917 
918 #else // def FLOW123D_DEBUG_PROFILER
919 
921  static Profiler * _instance = new Profiler();
922  return _instance;
923  }
924 
925 // Profiler* Profiler::_instance = NULL;
926 
927 // void Profiler::initialize() {
928 // if (_instance == NULL) {
929 // _instance = new Profiler();
930 // set_memory_monitoring(true, true);
931 // }
932 // }
933 
935  if (Profiler::instance()) {
936  ASSERT(Profiler::instance()->actual_node==0)(Profiler::instance()->timers_[Profiler::instance()->actual_node].tag())
937  .error("Forbidden to uninitialize the Profiler when actual timer is not zero.");
938  set_memory_monitoring(false, false);
939  Profiler::instance()->stop_timer(0);
940  // delete _instance;
941  // _instance = NULL;
942  }
943 }
944 
945 
946 #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:54
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:148
#define ASSERT(expr)
Allow use shorter versions of macro names if these names is not used with external library...
Definition: asserts.hh:347
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
#define ASSERT_LT(a, b)
Definition of comparative assert macro (Less Than)
Definition: asserts.hh:296
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
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:328
void set_task_info(string description, int size)
void notify_malloc(const size_t size)