C++: keeping track of elapsed time - c++

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).

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

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.

Related

Game clock and Sleep (C++)

I'm currently making a small console game. At the end of the game loop is another loop that doesn't release until 1/100s after the iteration's begin time.
Of course that uses up a lot of CPU, so I placed
Sleep(1);
at the end to solve it. I thought everything was right until I ran the game on a 2005 XP laptop... and it was really slow.
When I removed the Sleep command, the game worked perfectly on both computers, but now I have the CPU usage problem.
Does anyone have a good solution for this?
So I found out that the problem was with Windows NT (2000, XP, 2003) sleep granularity that was around 15 ms.. if anyone also struggles with this type of problem, here's how to solve it:
timeBeginPeriod(1); //from windows.h
Call it once at the beginning of the main() function. This affects a few things including Sleep() so that it's actually 'sleeping' for an exact millisecond.
timeEndPeriod(1); //on exit
Of course I was developing the game on Windows 7 all time and thought everything was right, so apparently Windows 6.0+ removed this problem... but it's still useful considering the fact that a lot of people still use XP
You should use std::this_thread::sleep_for in header <thread> for this, along with std::chrono stuff. Maybe something like this:
while(...)
{
auto begin = std::chrono::steady_clock::now();
// your code
auto end = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin);
std::this_thread::sleep_for(std::chrono::milliseconds(10) - duration);
}
If your code doesn't consume much time during one iteration or if each iteration takes constant time, you can leave alone the measuring and just put there some constant:
std::this_thread::sleep_for(std::chrono::milliseconds(8));
Sounds like the older laptop just takes more time to do all your processes then it sleeps for 1 millisecond.
You should include a library that tells time,
get the current time at the start of the program / start of the loop then at the end of the loop / program compare the difference of your starting time and the current to the amount of time you want. If it's lower than the amount of time you want (let's say 8 milliseconds) tell it to sleep for minimumTime - currentTime - recordedTime (the variable you set at the start of the loop)
I've done this for my own game in SDL2, SDL_GetTicks() just finds the amount of milliseconds the program has been running and "frametime" is the time at the start of the main game loop. This is how I keep my game running at a maximum of 60fps. This if statement should be modified and placed at the bottom of your program.
if( SDL_GetTicks() - frametime < MINFRAMETIME )
{
SDL_Delay( MINFRAMETIME - ( SDL_GetTicks() - frametime ) );
}
I think the standard library equivalent would be:
if( clock() - lastCheck < MIN_TIME )
{
sleep( MIN_TIME - ( clock() - lastCheck ) );
}

formatting clock_t variables to show as real time

I am currently looking for a solution with this project I am working on right now where I need to display the clock time of my sorting algorithms in clock ticks and real time. It seems I've got things setup ok, but when I am displaying the clock ticks and actual time I can't get the actual time to display 3 places after the decimal. Here is the code I have setup for the clock stuff (with the necessary header files)
// get beginning time
beginning = clock();
// --- Function to be clocked ---
// get ending time
ending = clock();
// set clock variables
elapsed = ending - beginning;
totalTime = (elapsed / CLK_TCK);
Some of my data is coming out looking like this when I go to display with cout,
Number of items - Elapsed Clock - Elapsed Time
100000 - 11400 - 11
Where I want it to look like this,
Number of items - Elapsed Clock - Elapsed Time
100000 - 11401 - 11.401
Sorry I know my formatting for this question is awful. Anyone have any advice?
#define __CLOCK_T_TYPE __SYSCALL_SLONG_TYPE
so clock() gives a long and you want a double... maybe som type cast would help here.

How to track total time of program?

Normally in an IDE, when you run a program the IDE will tell you the total amount of time that it took to run the program. Is there a way to get the total amount of time that it takes to run a program when using the terminal in Unix/Linux to compile and run?
I'm aware of ctime which allows for getting the total time since 1970, however I want to get just the time that it takes for the program to run.
You can start programs with time:
[:~/tmp] $ time sleep 1
real 0m1.007s
user 0m0.001s
sys 0m0.003s
You are on the right track! You can get the current time and subtract it from the end time of your program. The code below illustrated:
time_t begin = time(0); // get current time
// Do Stuff //
time_t end = time(0); // get current time
// Show number of seconds that have passed since program began //
std::cout << end - begin << std::endl;
NOTE: The time granularity is only a single second. If you need higher granularity, I suggest looking into precision timers such as QueryPerformanceCounter() on windows or clock_gettime() on linux. In both cases, the code will likely work very similarly.
As an addendum to mdsl's answer, if you want to get something close to that measurement in the program itself, you can get the time at the start of the program and get the time at the end of the program (as you said, in time since 1970) - then subtract the start time from the end time.

Timed memory tiles game. now works without timing

I have done a memory tiles program but i want it to be timed, i.e, the user shoud be able to play the game only for 2 mins. what do i do?
Also in linux sleep() does not work, what should we use for a delay??
I presume the game has a "main loop" somewhere.
At the beginning of the main loop (before the actual loop), take the current time, call this start_time. Then in each iteration of the loop, take the current time again, call this now. The elapsed time is elapsed_time = now - start_time;. Assuming time is in seconds, then if (elapsed_time >= 120) { ... end game ... } would do the trick.

Running a timer in cpp,parallel to a program under execution

I'm running an OpenCV application on visual studio on a windows 7 machine. As part of the end application, I need a timer running in parallel to the OpenCV application which is under execution. The OpenCV application has real time video capture as input to a eye blink detection algorithm. The OpenCV code must be running continuously and can not be paused or stopped. However, to find the interval between blinks, I need to have a timer running after each blink. So the timer has to run while blinks are detected. I have gone through the SetTimer and CreateTimerQueueTimer functions and was unable to obtain a clear understanding of how to go about this. Is there any other way of running a timer in a c++ program? Any suggestions and solutions will be highly appreciated.
Why do you need a timer to calculate the interval between the blinks? Can't you just store the current time at each blink and subtract it from the previous?
With c++11 you can use std::chrono to make a simple timer:
auto start = std::chrono::high_resolution_clock::now();
// do processing here
auto end = std::chrono::high_resolution_clock::now();
std::cout << "time was " <<
std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
Edit in response to the comment on the other answer, you could do the following:
...
auto take = (end - start);
if(take > std::chrono::nanoseconds(x)) {
// ... do whatever you want here
}
Oh and one thing to mention is that you can replace the nanoseconds with any other time unit.