PetaVision  Alpha
Clock.cpp
1 /*
2  * Clock.cpp
3  *
4  * Created on: Jun 6, 2016
5  * Author: pschultz
6  */
7 
8 #include "Clock.hpp"
9 
10 namespace PV {
11 
12 void Clock::start_clock() {
13  struct rusage r;
14  struct timeval t;
15 
16  m_start = clock();
17 
18  getrusage(RUSAGE_SELF, &r);
19  m_rstart = r.ru_utime.tv_sec + r.ru_utime.tv_usec * 1.0e-6;
20 
21  gettimeofday(&t, (struct timezone *)0);
22  m_tstart = t.tv_sec + t.tv_usec * 1.0e-6;
23  m_tv_start = t;
24 #ifdef MACH_TIMER
25  m_mach_start = mach_absolute_time();
26 #endif
27 
28 #ifdef CYCLE_TIMER
29  READ_CYCLE_COUNTER(cycle_start);
30 #endif
31 }
32 
33 void Clock::stop_clock() {
34  struct rusage r;
35  struct timeval t;
36 
37  m_end = clock();
38 
39  getrusage(RUSAGE_SELF, &r);
40  m_rend = r.ru_utime.tv_sec + r.ru_utime.tv_usec * 1.0e-6;
41 
42  gettimeofday(&t, (struct timezone *)0);
43  m_tend = t.tv_sec + t.tv_usec * 1.0e-6;
44  m_tv_end = t;
45 
46 #ifdef MACH_TIMER
47  m_mach_end = mach_absolute_time();
48 #endif
49 
50 #ifdef CYCLE_TIMER
51  READ_CYCLE_COUNTER(m_cycle_end);
52 #endif
53 }
54 
55 void Clock::print_elapsed(std::ostream &stream) {
56  std::streamsize w = stream.width(1);
57  std::streamsize p = stream.precision(2);
58  stream << " " << (float)((double)(m_end - m_start) / CLOCKS_PER_SEC)
59  << " seconds elapsed (clock())\n";
60  stream << " " << (float)(m_rend - m_rstart) << " seconds elapsed (CPU)\n";
61  stream << " " << (float)(m_tend - m_tstart) << " seconds elapsed (wallclock)\n";
62  stream.width(w);
63  stream.precision(p);
64 
65 #ifdef MACH_TIMER
66  uint64_t mach_elapsed = mach_time_to_sec(m_mach_end - m_mach_start);
67  stream << "Mach processor cycle time = " << (float)m_mach_elapsed << "\n";
68 #endif
69 
70 #ifdef CYCLE_TIMER
71  uint64_t cycle_elapsed = m_cycle_end - m_cycle_start;
72  stream << cycle_elapsed << " cycles elapsed\n";
73  stream << (float) ((double)cycle_elapsed/(double)CYCLES_PER_SEC << " seconds elapsed (cycle timer)\n";
74 #endif
75 }
76 
77 #ifdef MACH_TIMER
78 double Clock::elapsed_time() { return mach_time_to_sec(mach_absolute_time() - mach_start); }
79 
80 double Clock::mach_time_to_sec(uint64_t elapsed) {
81  if (sTimebaseInfo.denom == 0) {
82  // initialize (yuk, hope it isn't some stray value)
83  (void)mach_timebase_info(&sTimebaseInfo);
84  }
85 
86  double ms = (double)(elapsed) / 1.0e9;
87  ms *= sTimebaseInfo.numer / sTimebaseInfo.denom;
88 
89  return ms;
90 }
91 
92 #endif // MACH_TIMER
93 
94 } // namespace PV