C++ calculating time intervals - c++

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.

Related

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.

Timestamp in milliseconds gives me 10 digit in C++?

I am trying to retrieve Current Time in milliseconds using boost library.. Below is my code which I am using to get the current time in milliseconds.
boost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration duration( time.time_of_day() );
std::cout << duration.total_milliseconds() << std::endl;
uint64_t timestampInMilliseconds = duration.total_milliseconds() // will this work or not?
std::cout << timestampInMilliseconds << std::endl;
But this prints out in 10 digit which is like 17227676.. I am running my code on my ubuntu machine.. And I believe it is always 13 digit long value? Isn't so?
After computing the timestamp in milliseconds, I need to use below formula on that -
int end = (timestampInMilliseconds / (60 * 60 * 1000 * 24)) % 14
But somehow I am not sure whether timestampInMilliseconds which I am getting is right or not?
First of all should I be using boost::posix or not? I am assuming there might be some better way.. I am running code on my ubuntu machine..
Update:-
As this piece of bash script prints out timestampInMilliseconds which is of 13 digit..
date +%s%N | cut -b1-13
The problem here is that you use time_of_day() which returns (from this reference)
Get the time offset in the day.
So from the value you provided in the question I can deduce that you ran this program at 4:47 am.
Instead you might want to use e.g. the to_tm() to get a struct tm and construct your time in milliseconds from there.
Also note that the %s format to the date command (and the strftime function) is the number of seconds since the epoch, not the number of milliseconds.
If you look at the tm structure, you will see that it has the number of years (since 1900, so subtract 70 here), days into the year, and then hours,, minutes and seconds into the day. All these can be used to calculate the time in seconds easily.
And that in seconds is the problem here. If you look at e.g. the POSIX time function you see that
shall return the value of time in seconds since the Epoch
If you want an accurate millisecond resolution you simply can't use the ptime (where the p stands for POSIX). If you want millisecond resolution you either have to use e.g. system functions that returns the time in higher resolutions (like gettimeofday), or you can see e.g. this old SO answer.

How can I periodically execute some function if this function takes along time to run (less than peroid)

I want to run a function for example func() exactly 1 time per second. However the running time of func() is about 500 ms. How Can I do that? I know if the running time of the function is low, I can write a while loop in func() and sleep() for 1 second after each execution. But now, the running time is high. What should I do to ensure the func() run exactly 1 time per second? Thanks.
Yo do:
Take the current time in start_time.
Perform your job
Take the current time in end_time
Wait for (1 second + start_time - end_time)
That way, you can perform your tasks every seconds reliably. If the task takes less time, you will wait longer and vice versa. Note however that this assumes that your task takes always less than 1 sec. to execute. In the real code, you want to check for that before the sleep statement.
Implementation details depend on the platform.
Note that using this method still results in a small drift due to the time it takes to compute step 4. A more accurate alternative would be to synchronize on integer multiple of one second. That way, over 1000s of cycles you would not drift.
It depends on the level of accuracy you need.
If you want a brute, easy to code solution, you can get the time before first run of the function and save it in some variable (start_time). Create repeat index count variable (repeat_number) that stores next repeat number. Then you can do kinda this:
1) next_run_time = ++repeat_number*1sec + start_time;
2) func();
3) wait_time = next_run_time - current_time;
4) sleep(wait_time)
5) goto 1;
This approach disables accumulation of time error on each iteration.
But for the real application you should find some event framework or library.

sleep for many days with resolution of microseconds

Is there a way to put a thread to sleep for many days with a resolution of microseconds? usleep can only put the thread to sleep for 1000000 and sleep works in second steps. Is there a way to, may be, use both sleep and usleep to achieve this?
While it is not yet time to wake up:
Check the current time
Go to sleep a bit shorter than when you want to wake up.
This way, you can periodically check the time, increasingly faster and more detailed as you reach the time you want to wake up.
Just divide the large sleep in several small sleep periods.
int64_t time_to_sleep = ...;
int peroid_to_sleep = ...;
while( time_to_sleep > 0 )
{
usleep( period_slept );
time_to_sleep -= period_slept;
}