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