cpu_timer.cc
Go to the documentation of this file.
1 // ======================================================================
2 //
3 // cpu_timer: Measure the cpu and wallclock elapsed times
4 //
5 // ======================================================================
6 
7 #include "cetlib/cpu_timer.h"
8 
9 #include "cetlib_except/exception.h"
10 #include <cerrno>
11 #include <sys/resource.h>
12 
13 using namespace cet;
14 
15 namespace {
16 
17  // ======================================================================
18  // helpers:
19 
20  timeval
21  real_now()
22  {
23  timeval now;
24  gettimeofday(&now, 0);
25  return now;
26  }
27 
28  timeval
29  cpu_now()
30  {
31  rusage theUsage;
32  if (getrusage(RUSAGE_SELF, &theUsage) != 0) {
33  throw exception("cpu_timer", "Failure in get_current_stats") << errno;
34  }
35 
36  timeval now;
37  now.tv_sec = theUsage.ru_stime.tv_sec + theUsage.ru_utime.tv_sec;
38  now.tv_usec = theUsage.ru_stime.tv_usec + theUsage.ru_utime.tv_usec;
39  return now;
40  }
41 
42  double
43  operator-(timeval const& t1, timeval const& t2)
44  {
45  double constexpr microsec_per_sec{1E-6};
46  return t1.tv_sec - t2.tv_sec + (t1.tv_usec - t2.tv_usec) * microsec_per_sec;
47  }
48 }
49 
50 // ======================================================================
51 // accessors:
52 
53 double
55 {
56  return real_now() - start_real_time_;
57 }
58 
59 double
61 {
62  return cpu_now() - start_cpu_time_;
63 }
64 
65 double
67 {
70 }
71 
72 double
74 {
77 }
78 
79 // ======================================================================
80 // mutators:
81 
82 void
84 {
85  if (!is_stopped())
86  return;
87  start_real_time_ = real_now();
88  start_cpu_time_ = cpu_now();
89  is_running_ = true;
90 }
91 
92 void
94 {
95  if (!is_running())
96  return;
99  is_running_ = false;
100 }
101 
102 void
104 {
106  accumulated_cpu_time_ = 0.0;
107 }
108 
109 // ======================================================================
double accumulated_cpu_time_
Definition: cpu_timer.h:60
timeval start_cpu_time_
Definition: cpu_timer.h:58
int errno
Contains the last error code.
Definition: structcmd.h:53
QuadExpr operator-(double v, const QuadExpr &e)
Definition: QuadExpr.h:38
timeval start_real_time_
Definition: cpu_timer.h:57
bool is_running() const
Definition: cpu_timer.h:67
bool is_running_
Definition: cpu_timer.h:56
double accumulated_cpu_time() const
Definition: cpu_timer.cc:73
double elapsed_cpu_time() const
Definition: cpu_timer.cc:60
double accumulated_real_time_
Definition: cpu_timer.h:59
bool is_stopped() const
Definition: cpu_timer.h:73
double accumulated_real_time() const
Definition: cpu_timer.cc:66
double elapsed_real_time() const
Definition: cpu_timer.cc:54
int gettimeofday(struct timeval *, struct timezone *)
void start()
Definition: cpu_timer.cc:83
cet::coded_exception< error, detail::translate > exception
Definition: exception.h:33