C++ Portable Timing
2017-09-30 本文已影响16人
Brent姜
自己写一个简单的:
#pragma once
// for linux nanoseconds, use:
// int clock_getcpuclockid(pid_t pid, clockid_t *clock_id);
#ifdef LINUX
#include <sys/time.h>
#else
#if (!defined _INC_WINAPIFAMILY)
#include <Windows.h>
#endif
#endif
class StopWatch
{
public:
StopWatch()
#ifdef LINUX
: timer(0)
#else
: elapsed_(0)
#endif
{
#ifdef LINUX
#else
QueryPerformanceFrequency(&freq_);
#endif
}
~StopWatch() {}
public:
void start()
{
#ifdef LINUX
gettimeofday(&start, NULL);
#else
QueryPerformanceCounter(&begin_time_);
#endif
}
void stop()
{
#ifdef LINUX
gettimeofday(&end, NULL);
timer = 1000000 * (end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec;
#else
LARGE_INTEGER end_time;
QueryPerformanceCounter(&end_time);
elapsed_ += (end_time.QuadPart - begin_time_.QuadPart) * 1000000 / freq_.QuadPart;
#endif
}
void restart()
{
#ifdef LINUX
timer = 0;
#else
elapsed_ = 0;
#endif
start();
}
//微秒
double elapsed() const
{
#ifdef LINUX
return static_cast<double>(timer);
#else
return static_cast<double>(elapsed_);
#endif
}
//毫秒
double elapsed_ms() const
{
#ifdef LINUX
return static_cast<double>(timer) / 1000.0;
#else
return static_cast<double>(elapsed_) / 1000.0;
#endif
}
//秒
double elapsed_second() const
{
#ifdef LINUX
return static_cast<double>(timer) / 1000000.0;
#else
return static_cast<double>(elapsed_) / 1000000.0;
#endif
}
private:
#ifdef LINUX
struct timeval start;
struct timeval end;
unsigned long timer;
#else
LARGE_INTEGER freq_;
LARGE_INTEGER begin_time_;
long long elapsed_;
#endif
};