2

I am currently trying to re-write some software in C++ from an old python code. In the python version I used to have timers like these:

from time import time, sleep

t_start = time()
while (time()-t_start < 5) # 5 second timer
    # do some stuff
    sleep(0.001) #Don't slam the CPU

sleep(1)
print time()-t_start # would print something like 6.123145 notice the precision!

However, in C++ when I try to use time(0) from < time.h > I can only get precision in seconds as an integer, not a float.

#include <time.h>
#include <iostream>

time_t t_start = time(0)
while (time(0) - t_start < 5) // again a 5 second timer.
{
    // Do some stuff 
    sleep(0.001) // long boost sleep method.
}
sleep(1);
std::cout << time(0)-t_start; // Prints 6 instead of 6.123145

I have also tried gettimeofday(struct, NULL) from < sys/time.h > however whenever I sleep the program with boost::this_thread::sleep it doesn't count that time...

I hope somebody here has come across a similar problem and found a solution.

Also, I really do need the dt in at least millisecond precision, because in the

// Do some stuff

part of the code I may break out of the while loop early and I need to know how long I was inside, etc.

Thank you for reading!

ch0l1n3
  • 275
  • 3
  • 9
  • 4
    You are not getting a floating point result, because time_t is integer type according to http://stackoverflow.com/questions/471248/what-is-ultimately-a-time-t-typedef-to – Tony J Feb 19 '15 at 07:26

1 Answers1

0

gettimeofday() is known to have issues when there are discontinuous jumps in the system time.

For portable milisecond precision have a look at chrono::high_resolution_clock()

Here a little snippet:

chrono::high_resolution_clock::time_point ts = chrono::high_resolution_clock::now();
chrono::high_resolution_clock::time_point te = chrono::high_resolution_clock::now();
// ... do something ...
cout << "took " << chrono::duration_cast<chrono::milliseconds>(te - ts).count() << " millisecs\n";

Please note the real clock resolution is bound to the operating system. For instance, on windows you usually have a 15ms precision, and you can go beyond this constraint only by using platform dependent clocking systems.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • Is it possible to store the difference as a double?? – ch0l1n3 Feb 19 '15 at 07:46
  • 1
    needs to mention boost::chrono for Windows (I believe the MSVS2015 CTP might fix the resolution?). – sehe Feb 19 '15 at 07:46
  • 1
    @ch0l1n3 `c::duration_cast(duration).count()/1000.0` e.g. (c=std::chrono) – sehe Feb 19 '15 at 07:47
  • so like this? double dt = chrono::duration_cast(te - ts).count()/1000.0 Also, i'm using linux, so perhaps the resolution issue is different! – ch0l1n3 Feb 19 '15 at 07:50
  • My understanding is that `chrono::high_resolution_clock` is not guaranteed to be 'steady' and not 'jump around'. – Persixty Feb 19 '15 at 07:53