Skip to content

Instantly share code, notes, and snippets.

@kimsama
Last active May 18, 2020 05:15
Show Gist options
  • Save kimsama/9a5c1213b0391b6fe7da4e412bcca981 to your computer and use it in GitHub Desktop.
Save kimsama/9a5c1213b0391b6fe7da4e412bcca981 to your computer and use it in GitHub Desktop.
A simpler timer class and its demo, using QueryPerformanceCounter. (therefore works only on windows platform)
#include "SimpleTimer.h"
/**
Initialize, call application start time before updating frame.
*/
void SimpleTimer::start()
{
// from MSDN: On systems that run Windows XP or later,
// the function will always succeed and will thus never return zero.
(void)QueryPerformanceFrequency(&freq);
(void)QueryPerformanceCounter(&start_time);
last_time = start_time;
}
/**
Return elapsed time as miliseconds.
*/
float SimpleTimer::tick()
{
float dt;
LARGE_INTEGER current_time;
QueryPerformanceCounter(&current_time);
if (last_time.QuadPart == start_time.QuadPart)
dt = 1.0f / 60.0f;
else
dt = static_cast<float>(static_cast<double>(current_time.QuadPart - last_time.QuadPart) / static_cast<double>(freq.QuadPart));
last_time = current_time;
return dt;
}
/**
Return elapsed time as miliseconds.
*/
float SimpleTimer::total()
{
float dt;
LARGE_INTEGER current_time;
QueryPerformanceCounter(&current_time);
if (last_time.QuadPart == start_time.QuadPart)
dt = 1.0f / 60.0f;
else
dt = static_cast<float>(static_cast<double>(current_time.QuadPart - start_time.QuadPart) / static_cast<double>(freq.QuadPart));
last_time = current_time;
return dt;
}
#pragma once
#include <windows.h>
/**
A simple timer(only for windows platform)
*/
class SimpleTimer
{
public:
void start();
float tick();
float total();
private:
LARGE_INTEGER freq;
LARGE_INTEGER start_time;
LARGE_INTEGER last_time;
};
#include <iostream>
#include "SimpleTimer.h"
int main()
{
SimpleTimer timer;
timer.start();
while (1)
{
// put elapsed time at every 20ms.
// it will put approx. 0.020xxx.
float elapsed = timer.tick();
printf("elapsed: %f\n", elapsed);
// break after passing 2sec.
float total = timer.total();
if (total > 2.0)
break;
// sleep 20ms.
Sleep(20);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment