Impala
Impalaistheopensource,nativeanalyticdatabaseforApacheHadoop.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
stopwatch.h
Go to the documentation of this file.
1 // Copyright 2012 Cloudera Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 
16 #ifndef IMPALA_UTIL_STOPWATCH_H
17 #define IMPALA_UTIL_STOPWATCH_H
18 
19 #include <boost/cstdint.hpp>
20 #include <time.h>
21 
22 namespace impala {
23 
28 class StopWatch {
29  public:
31  total_time_ = 0;
32  running_ = false;
33  }
34 
35  void Start() {
36  if (!running_) {
37  start_ = Rdtsc();
38  running_ = true;
39  }
40  }
41 
42  void Stop() {
43  if (running_) {
44  total_time_ += Rdtsc() - start_;
45  running_ = false;
46  }
47  }
48 
51  return running_ ? Rdtsc() - start_ : total_time_;
52  }
53 
54  static uint64_t Rdtsc() {
55  uint32_t lo, hi;
56  __asm__ __volatile__ (
57  "xorl %%eax,%%eax \n cpuid"
58  ::: "%rax", "%rbx", "%rcx", "%rdx");
59  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
60  return (uint64_t)hi << 32 | lo;
61  }
62 
63  private:
65  bool running_;
66 };
67 
75  public:
77  total_time_ = 0;
78  running_ = false;
79  }
80 
81  void Start() {
82  if (!running_) {
83  clock_gettime(CLOCK_MONOTONIC, &start_);
84  running_ = true;
85  }
86  }
87 
88  void Stop() {
89  if (running_) {
91  running_ = false;
92  }
93  }
94 
97  uint64_t ret = ElapsedTime();
98  if (running_) {
99  clock_gettime(CLOCK_MONOTONIC, &start_);
100  }
101  return ret;
102  }
103 
106  if (!running_) return total_time_;
107  timespec end;
108  clock_gettime(CLOCK_MONOTONIC, &end);
109  return (end.tv_sec - start_.tv_sec) * 1000L * 1000L * 1000L +
110  (end.tv_nsec - start_.tv_nsec);
111  }
112 
113  private:
114  timespec start_;
115  uint64_t total_time_; // in nanosec
116  bool running_;
117 };
118 
119 }
120 
121 #endif
uint64_t ElapsedTime() const
Returns time in cpu ticks.
Definition: stopwatch.h:50
uint64_t total_time_
Definition: stopwatch.h:64
uint64_t start_
Definition: stopwatch.h:64
uint64_t Reset()
Restarts the timer. Returns the elapsed time until this point.
Definition: stopwatch.h:96
uint64_t ElapsedTime() const
Returns time in nanosecond.
Definition: stopwatch.h:105
static uint64_t Rdtsc()
Definition: stopwatch.h:54