timer.h revision 2c01beb4
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 302c01beb4SShuo Chen double seconds() const 312c01beb4SShuo Chen { 322c01beb4SShuo Chen return total_ / 1e9; 332c01beb4SShuo Chen } 342c01beb4SShuo Chen 352c01beb4SShuo Chen static int64_t gettime() 362c01beb4SShuo Chen { 372c01beb4SShuo Chen struct timespec ts; 382c01beb4SShuo Chen clock_gettime(CLOCK_MONOTONIC_RAW, &ts); 392c01beb4SShuo Chen return ts.tv_sec * 1e9 + ts.tv_nsec; 402c01beb4SShuo Chen } 412c01beb4SShuo Chen 422c01beb4SShuo Chen private: 432c01beb4SShuo Chen int64_t start_, total_; 442c01beb4SShuo Chen}; 45