formatting clock_t variables to show as real time - c++

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.

Related

API to capture thread's CPU time

I want to measure the CPU time, not elapsed time on a thread. For example, if a thread is waiting or sleeping, it shouldn't count as CPU time because the thread is not in runnable state. So I got the following link to get CPU time. However, it seems to be capturing the elapsed time instead based on my test below (I expect cpu_time_used should be close to 0 but it is actually 2).What am I missing?
https://www.gnu.org/software/libc/manual/html_node/CPU-Time.html
#include <time.h>
clock_t start, end;
double cpu_time_used;
start = clock();
std::this_thread::sleep_for (std::chrono::seconds(2));
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
Note that clock() measures in units of core-time, i.e. CLOCKS_PER_SEC clock() ticks represent one second of computation on one processor, so it indicates the amount of time used by the process over all threads. So, if there is another thread running during the sleep it will still be increasing the clock count -- if there are two threads in total the clock count will indicate 2 seconds have elapsed, like you have shown. If the sleeping thread is the only thread, you get a small amount of time, like #NateEldredge reports. On Linux you can query or setup a timer on CLOCK_THREAD_CPUTIME_ID instead, like #KamilCuk said.

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 ) );
}

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.

C++ calculating time intervals

I want to calculate time intervals (in 1/10th of 1 second) between some events happening in my program. Thus I use clock function for these needs like follows:
clock_t begin;
clock_t now;
clock_t diff;
begin = clock();
while ( 1 )
{
now = clock();
diff = now - begin;
cout << diff / CLOCKS_PER_SEC << "\n";
//usleep ( 1000000 );
};
I expect the program to print 0 for 1 second, then 1 for 1 sec., then 2 for 1 sec. and so on... In fact it prints 0 for about 8 seconds, then 1 for about 8 seconds and so on...
By the way, if I add usleep in order program prints only 1 time per second, it prints only 0 all way long...
Great thanks for help!
The clock() function returns the amount of CPU time charged to your program. When you are blocked inside a usleep() call, no time is being charged to you, making it very clear why your time never seems to increase. As to why you seem to be taking 8 seconds to be charged one second -- there are other things going on within your system, consuming CPU time that you would like to be consuming but you must share the processor. clock() cannot be used to measure the passage of real time.
I bet your printing so much to stdout that old prints are getting buffered. The buffer is growing and the output to the console can't keep up with your tight loop. By adding the sleep you're allowing the buffer some time to flush and catch up. So even though its 8 seconds into your program, your printing stuff from 8 seconds ago.
I'd suggest putting the actual timestamp into the print statement. See if the timestamp is lagging significantly from the actual time.
If you're able to use boost, checkout the Boost Timers library.
Maybe you have to typecast it to double.
cout << (double)(diff / CLOCKS_PER_SEC) << "\n";
Integers get rounded, probably to 0 in your case.
Read about the time() function.

C++: keeping track of elapsed time

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.