0

I'm looking for a way to be able to know how much time it's been since my program was started, at any given time. A sort of timer that would keep running while the main code is doing everything else, and that can be called at any time.

The context is an OpenGL application on Windows, and as well as knowing which keyboard keys are being pressed (using glutKeyboardFunc), I'd like to know when exactly each key is pressed. All of this info is written into an XML file that will later be used to replay everything the user did. (sort of like the replay functionality in a car racing game, but more simple).

genpfault
  • 51,148
  • 11
  • 85
  • 139
John
  • 61
  • 2
  • 3

2 Answers2

6

C++ 11:

#include <iostream>
#include <chrono>

auto start = std::chrono::system_clock::now();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";

Code taken from en.cppreference.com and simplified.

Old answer:
GetTickCount() in windows.h returns ticks(miliseconds) elapsed. When your app starts, call this function and store its value, then whenever you need to know elapsed time since your program start, call this method again and subtract its value from start value.

int start = GetTickCount(); // At Program Start

int elapsed = GetTickCount() - start; // This is elapsed time since start of your program
atoMerz
  • 7,534
  • 16
  • 61
  • 101
5

You don't need a timer for this, you save the timestamp at start of the app with time(0). And the you do the same each time you want to measure the time and you can just to init_time - current_time and you'll get the time lapse.

dwarfy
  • 3,076
  • 18
  • 22