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!