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 1:

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
    struct timeval start, end;

    long mtime, seconds, useconds;    

    gettimeofday(&start, NULL);
    usleep(2000);
    gettimeofday(&end, NULL);

    seconds  = end.tv_sec  - start.tv_sec;
    useconds = end.tv_usec - start.tv_usec;

    mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

    printf("Elapsed time: %ld milliseconds\n", mtime);

    return 0;
}

Solution 2:

Please note that clock does not measure wall clock time. That means if your program takes 5 seconds, clock will not measure 5 seconds necessarily, but could more (your program could run multiple threads and so could consume more CPU than real time) or less. It measures an approximation of CPU time used. To see the difference consider this code

#include <iostream>
#include <ctime>
#include <unistd.h>

int main() {
    std::clock_t a = std::clock();
    sleep(5); // sleep 5s
    std::clock_t b = std::clock();

    std::cout << "difference: " << (b - a) << std::endl;
    return 0;
}

It outputs on my system

$ difference: 0

Because all we did was sleeping and not using any CPU time! However, using gettimeofday we get what we want (?)

#include <iostream>
#include <ctime>
#include <unistd.h>
#include <sys/time.h>

int main() {
    timeval a;
    timeval b;

    gettimeofday(&a, 0);
    sleep(5); // sleep 5s
    gettimeofday(&b, 0);

    std::cout << "difference: " << (b.tv_sec - a.tv_sec) << std::endl;
    return 0;
}

Outputs on my system

$ difference: 5

If you need more precision but want to get CPU time, then you can consider using the getrusage function.