On Windows, clock()
returns the time in milliseconds, but on this Linux box I'm working on, it rounds it to the nearest 1000 so the precision is only to the "second" level and not to the milliseconds level.
I found a solution with Qt using the QTime
class, instantiating an object and calling start()
on it then calling elapsed()
to get the number of milliseconds elapsed.
I got kind of lucky because I'm working with Qt to begin with, but I'd like a solution that doesn't rely on third party libraries,
Is there no standard way to do this?
UPDATE
Please don't recommend Boost ..
If Boost and Qt can do it, surely it's not magic, there must be something standard that they're using!
clock() doesn't return milliseconds or seconds on linux. Usually clock() returns microseconds on a linux system. The proper way to interpret the value returned by clock() is to divide it by CLOCKS_PER_SEC to figure out how much time has passed.
gettimeofday - the problem is that will can have lower values if you change you hardware clock (with NTP for example) Boost - not available for this project clock() - usually returns a 4 bytes integer, wich means that its a low capacity, and after some time it returns negative numbers.
I prefer to create my own class and update each 10 miliseconds, so this way is more flexible, and I can even improve it to have subscribers.
to refresh it I use setitimer:
Look at setitimer and the ITIMER_VIRTUAL and ITIMER_REAL.
Don't use the alarm or ualarm functions, you will have low precision when your process get a hard work.
With C++11 and
std::chrono::high_resolution_clock
you can do this:Output:
Link to demo: http://cpp.sh/2zdtu
In the POSIX standard
clock
has its return value defined in terms of the CLOCKS_PER_SEC symbol and an implementation is free to define this in any convenient fashion. Under Linux, I have had good luck with thetimes()
function.I prefer the Boost Timer library for its simplicity, but if you don't want to use third-parrty libraries, using clock() seems reasonable.
This should work...tested on a mac...
Yeah...run it twice and subtract...