Search code examples
c++timerclock

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly


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!


Solution

  • You could use gettimeofday at the start and end of your method and then difference the two return structs. You'll get a structure like the following:

    struct timeval {
      time_t tv_sec;
      suseconds_t tv_usec;
    }
    

    EDIT: As the two comments below suggest, clock_gettime(CLOCK_MONOTONIC) is a much better choice if you have it available, which should be almost everywhere these days.

    EDIT: Someone else commented that you can also use modern C++ with std::chrono::high_resolution_clock, but that isn't guaranteed to be monotonic. Use steady_clock instead.