Stxxl  1.2.1
timer.h
1 /***************************************************************************
2  * include/stxxl/bits/common/timer.h
3  *
4  * Part of the STXXL. See http://stxxl.sourceforge.net
5  *
6  * Copyright (C) 2002, 2005 Roman Dementiev <dementiev@mpi-sb.mpg.de>
7  *
8  * Distributed under the Boost Software License, Version 1.0.
9  * (See accompanying file LICENSE_1_0.txt or copy at
10  * http://www.boost.org/LICENSE_1_0.txt)
11  **************************************************************************/
12 
13 #ifndef STXXL_TIMER_HEADER
14 #define STXXL_TIMER_HEADER
15 
16 #ifdef STXXL_BOOST_TIMESTAMP
17  #include <boost/date_time/posix_time/posix_time.hpp>
18  #include <cmath>
19 #else
20  #include <ctime>
21  #include <sys/time.h>
22 #endif
23 
24 #include <stxxl/bits/namespace.h>
25 
26 
27 __STXXL_BEGIN_NAMESPACE
28 
30 inline double
31 timestamp()
32 {
33 #ifdef STXXL_BOOST_TIMESTAMP
34  boost::posix_time::ptime MyTime = boost::posix_time::microsec_clock::local_time();
35  boost::posix_time::time_duration Duration =
36  MyTime - boost::posix_time::time_from_string("1970-01-01 00:00:00.000");
37  double sec = double(Duration.hours()) * 3600. +
38  double(Duration.minutes()) * 60. +
39  double(Duration.seconds()) +
40  double(Duration.fractional_seconds()) / (pow(10., Duration.num_fractional_digits()));
41  return sec;
42 #else
43  struct timeval tp;
44  gettimeofday(&tp, NULL);
45  return double(tp.tv_sec) + tp.tv_usec / 1000000.;
46 #endif
47 }
48 
49 class timer
50 {
51  bool running;
52  double accumulated;
53  double last_clock;
54  inline double timestamp();
55 
56 public:
57  inline timer();
58  inline void start();
59  inline void stop();
60  inline void reset();
61  inline double seconds();
62  inline double mseconds();
63  inline double useconds();
64 };
65 
66 timer::timer() : running(false), accumulated(0.)
67 { }
68 
69 double timer::timestamp()
70 {
71  return stxxl::timestamp();
72 }
73 
74 void timer::start()
75 {
76  running = true;
77  last_clock = timestamp();
78 }
79 
80 void timer::stop()
81 {
82  running = false;
83  accumulated += timestamp() - last_clock;
84 }
85 
86 void timer::reset()
87 {
88  accumulated = 0.;
89  last_clock = timestamp();
90 }
91 
92 double timer::mseconds()
93 {
94  if (running)
95  return (accumulated + timestamp() - last_clock) * 1000.;
96 
97  return (accumulated * 1000.);
98 }
99 
100 double timer::useconds()
101 {
102  if (running)
103  return (accumulated + timestamp() - last_clock) * 1000000.;
104 
105  return (accumulated * 1000000.);
106 }
107 
108 double timer::seconds()
109 {
110  if (running)
111  return (accumulated + timestamp() - last_clock);
112 
113  return (accumulated);
114 }
115 
116 __STXXL_END_NAMESPACE
117 
118 #endif // !STXXL_TIMER_HEADER