HepMC3 event record library
Timer.h
1 // -*- C++ -*-
2 //
3 // This file is part of HepMC
4 // Copyright (C) 2014-2019 The HepMC collaboration (see AUTHORS for details)
5 //
6 #ifndef BENCHMARK_TIMER_H
7 #define BENCHMARK_TIMER_H
8 
9 #include <iostream>
10 
11 #if defined(_MSC_VER)
12 class Timer {
13 public:
14  /** Default constructor */
15  Timer(const char* name):m_name(name) { reset(); }
16  void start() {}
17  int elapsed_time() {return 0;}
18  int total_time() {return 0;}
19  void stop() {}
20  void reset() {}
21  void print() { printf("<sys/times.h> header is not present in MS Visual Studio. Dummy implementation of Timer class is used.\n");}
22 private:
23  const char *m_name;
24 
25 };
26 #else
27 #include <sys/times.h>
28 
29 class Timer {
30 public:
31  /** Default constructor */
32  Timer(const char* name):m_name(name) { reset(); }
33 
34  /** Start or restart the timer */
35  void start() {
36  times(&m_start);
37  }
38 
39  /** Get time elapsed since timer started */
40  int elapsed_time() {
41  times(&m_stop);
42  return 10*(m_stop.tms_utime - m_start.tms_utime + m_stop.tms_stime - m_start.tms_stime);
43  }
44 
45  /** Get total time counted by the timer */
46  int total_time() {
47  return 10*(m_stored.tms_utime + m_stored.tms_stime);
48  }
49 
50  /** Save end time and aggregate build-in clock */
51  void stop() {
52  // Do nothing if timer has not been started
53  if(m_start.tms_utime == 0) return;
54 
55  times(&m_stop);
56 
57  m_stored.tms_utime += m_stop.tms_utime - m_start.tms_utime;
58  m_stored.tms_stime += m_stop.tms_stime - m_start.tms_stime;
59 
60  m_start.tms_utime = 0;
61  m_start.tms_stime = 0;
62  }
63 
64  /** Reset the clock */
65  void reset() {
66  m_start.tms_utime = 0;
67  m_start.tms_stime = 0;
68  m_stored.tms_utime = 0;
69  m_stored.tms_stime = 0;
70  }
71 
72  /** Print time elapsed */
73  void print() {
74  std::cout << m_name << ":" << std::endl;
75  std::cout << " user: " << m_stored.tms_utime*10 << " ms" << std::endl;
76  std::cout << " system: " << m_stored.tms_stime*10 << " ms" << std::endl;
77  }
78 
79 private:
80  const char *m_name;
81  struct tms m_start,m_stop,m_stored;
82 };
83 #endif
84 #endif
void start()
Definition: Timer.h:35
Timer(const char *name)
Definition: Timer.h:32
void print()
Definition: Timer.h:73
int elapsed_time()
Definition: Timer.h:40
void stop()
Definition: Timer.h:51
int total_time()
Definition: Timer.h:46
Definition: Timer.h:29
void reset()
Definition: Timer.h:65