Skip to content

Instantly share code, notes, and snippets.

@murphypei
Last active April 27, 2020 03:36
Show Gist options
  • Save murphypei/feafd5bb4ff59f3a68cc1617c2c45811 to your computer and use it in GitHub Desktop.
Save murphypei/feafd5bb4ff59f3a68cc1617c2c45811 to your computer and use it in GitHub Desktop.
C++ auto time
#include "auto_time.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(WINDOWS)
#include <Windows.h>
#else
#include <sys/time.h>
#endif
namespace timer
{
Timer::Timer() { reset(); }
Timer::~Timer() {}
void Timer::reset()
{
#if defined(WINDOWS)
LARGE_INTEGER time, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&time);
uint64_t sec = time.QuadPart / freq.QuadPart;
uint64_t usec = (time.QuadPart % freq.QuadPart) * 1000000 / freq.QuadPart;
mLastResetTime = sec * 1000000 + usec;
#else
struct timeval Current;
gettimeofday(&Current, nullptr);
mLastResetTime = Current.tv_sec * 1000000 + Current.tv_usec;
#endif
}
uint64_t Timer::durationInUs()
{
#if defined(_MSC_VER)
LARGE_INTEGER time, freq;
QueryPerformanceCounter(&time);
QueryPerformanceFrequency(&freq);
uint64_t sec = time.QuadPart / freq.QuadPart;
uint64_t usec = (time.QuadPart % freq.QuadPart) * 1000000 / freq.QuadPart;
auto lastTime = sec * 1000000 + usec;
#else
struct timeval Current;
gettimeofday(&Current, nullptr);
auto lastTime = Current.tv_sec * 1000000 + Current.tv_usec;
#endif
return lastTime - mLastResetTime;
}
AutoTimer::AutoTime(const char *file, const char *func, int line) : Timer()
{
mFile = ::strdup(file);
mFunc = ::strdup(func);
mLine = line;
}
AutoTimer::~AutoTime()
{
auto timeInUs = durationInUs();
printf("%s::%s::%d, cost time: %f ms\n", mFile, mFunc, mLine, (float)timeInUs / 1000.0f);
free(mFile);
free(mFunc);
}
} // namespace timer
#include <stdint.h>
namespace timer
{
class Timer
{
public:
Timer();
~Timer();
Timer(const Timer &) = delete;
Timer(const Timer &&) = delete;
Timer &operator=(const Timer &) = delete;
Timer &operator=(const Timer &&) = delete;
// reset timer
void reset();
// get duration (us) from init or latest reset.
uint64_t durationInUs();
protected:
uint64_t mLastResetTime; // microseconds
};
class AutoTime : Time
{
public:
AutoTime(const char *file, const char *func, int line);
~AutoTime();
AutoTime(const AutoTimer &) = delete;
AutoTime(const AutoTimer &&) = delete;
AutoTime &operator=(const AutoTimer &) = delete;
AutoTime &operator=(const AutoTimer &&) = delete;
private:
int mLine;
char *mFunc;
char *mFile;
};
} // namespace timer
#ifdef OPEN_TIME_TRACE
#define AUTOTIME timer::AutoTime ___t(__FILE__, __FUNCTION__, __LINE__)
#else
#define AUTOTIMER
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment