timer.h revision d9e55939
12c01beb4SShuo Chen#pragma once
22c01beb4SShuo Chen#include <time.h>
32c01beb4SShuo Chen#include <sys/time.h>
42c01beb4SShuo Chen
52c01beb4SShuo Cheninline double now()
62c01beb4SShuo Chen{
72c01beb4SShuo Chen  struct timeval tv;
82c01beb4SShuo Chen  gettimeofday(&tv, NULL);
92c01beb4SShuo Chen  return tv.tv_sec + tv.tv_usec / 1e6;
102c01beb4SShuo Chen}
112c01beb4SShuo Chen
122c01beb4SShuo Chen
132c01beb4SShuo Chenstruct Timer
142c01beb4SShuo Chen{
152c01beb4SShuo Chen  Timer()
162c01beb4SShuo Chen      : start_(0), total_(0)
172c01beb4SShuo Chen  {
182c01beb4SShuo Chen  }
192c01beb4SShuo Chen
202c01beb4SShuo Chen  void start()
212c01beb4SShuo Chen  {
222c01beb4SShuo Chen    start_ = gettime();
232c01beb4SShuo Chen  }
242c01beb4SShuo Chen
252c01beb4SShuo Chen  void stop()
262c01beb4SShuo Chen  {
272c01beb4SShuo Chen    total_ += gettime() - start_;
282c01beb4SShuo Chen  }
292c01beb4SShuo Chen
30d9e55939SShuo Chen  void reset()
31d9e55939SShuo Chen  {
32d9e55939SShuo Chen    start_ = 0;
33d9e55939SShuo Chen    total_ = 0;
34d9e55939SShuo Chen  }
35d9e55939SShuo Chen
362c01beb4SShuo Chen  double seconds() const
372c01beb4SShuo Chen  {
382c01beb4SShuo Chen    return total_ / 1e9;
392c01beb4SShuo Chen  }
402c01beb4SShuo Chen
412c01beb4SShuo Chen  static int64_t gettime()
422c01beb4SShuo Chen  {
432c01beb4SShuo Chen    struct timespec ts;
442c01beb4SShuo Chen    clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
452c01beb4SShuo Chen    return ts.tv_sec * 1e9 + ts.tv_nsec;
462c01beb4SShuo Chen  }
472c01beb4SShuo Chen
482c01beb4SShuo Chen private:
492c01beb4SShuo Chen  int64_t start_, total_;
502c01beb4SShuo Chen};
51