Scid  4.6.5
timer.h
Go to the documentation of this file.
1 /*
2 * Copyright (C) 2014 Fulvio Benini
3 
4 * This file is part of Scid (Shane's Chess Information Database).
5 *
6 * Scid is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation.
9 *
10 * Scid is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with Scid. If not, see <http://www.gnu.org/licenses/>.
17 */
18 
19 #ifndef SCID_TIMER_H
20 #define SCID_TIMER_H
21 
22 #if CPP11_SUPPORT
23 
24 #include <chrono>
25 class Timer {
26  decltype(std::chrono::system_clock::now()) start_;
27 public:
28  Timer() { Reset(); }
29  void Reset() { start_ = std::chrono::system_clock::now(); }
30  long long MilliSecs (void) const {
31  auto t = std::chrono::system_clock::now();
32  return std::chrono::duration_cast<std::chrono::milliseconds>(t - start_).count();
33  }
34  long long CentiSecs () const { return MilliSecs() / 10; }
35 };
36 
37 template <class S>
38 auto operator<<(S& os, const Timer& timer) -> decltype(os) {
39  return os << timer.MilliSecs() << " milliseconds\n";
40 }
41 
42 /* Usage:
43 Timer t;
44 //do some stuff
45 std::cout << "Elapsed: " << t;
46 */
47 
48 
49 #else //no CPP11_SUPPORT
50 
51 class Timer {
52  long seconds_;
53  long milliseconds_;
54  static void set(long* sec, long* millisec);
55 
56 public:
57  Timer() { Reset (); }
58  void Reset() { set(&seconds_, &milliseconds_); }
59  int CentiSecs () { return MilliSecs() / 10; }
60  int MilliSecs () {
61  long sec, millisec;
62  set(&sec, &millisec);
63  return 1000 * (sec - seconds_) + (millisec - milliseconds_);
64  }
65 };
66 
67 
68 #ifndef _MSC_VER // Use gettimeofday() system call in Unix:
69 
70 #include <sys/time.h>
71 inline void Timer::set(long* sec, long* millisec) {
72  struct timeval timeOfDay;
73  gettimeofday (&timeOfDay, NULL);
74  *sec = timeOfDay.tv_sec;
75  *millisec = timeOfDay.tv_usec / 1000;
76 }
77 
78 #else // Use ftime() call in Windows:
79 
80 #include <sys/timeb.h>
81 inline void Timer::set(long* sec, long* millisec) {
82  struct timeb tb;
83  ftime (&tb);
84  *sec = tb.time;
85  *millisec = tb.millitm;
86 }
87 #endif //_MSC_VER
88 
89 #endif //CPP11_SUPPORT
90 
91 #endif //SCID_TIMER_H
Timer()
Definition: timer.h:57
Definition: timer.h:51
void Reset()
Definition: timer.h:58
int CentiSecs()
Definition: timer.h:59
int MilliSecs()
Definition: timer.h:60