views:

26613

answers:

12

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!

+2  A: 

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.

SoapBox
not in the box I'm working on! plus, I *am* dividing by CLOCKS_PER_SEC, but it's pointless because the resolution is only down to the second
hasen j
well to be fair, the units *is* microseconds (CLOCKS_PER_SEC is 1000000 on all POSIX systems). Just it has seconds resolution. :-P.
Evan Teran
+1  A: 

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 the times() function.

Jon Trauntvein
+13  A: 

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;
}
Adam Hawes
+1  A: 

I prefer the Boost Timer library for its simplicity, but if you don't want to use third-parrty libraries, using clock() seems reasonable.

Nick Presta
+1  A: 

This should work...tested on a mac...

#include <stdio.h>
#include <sys/time.h>

int main() {
        struct timeval tv;
        struct timezone tz;
        struct tm *tm;
        gettimeofday(&tv,&tz);
        tm=localtime(&tv.tv_sec);
        printf("StartTime: %d:%02d:%02d %d \n", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec);
}

Yeah...run it twice and subtract...

Jason Punyon
+27  A: 
#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;
}
CTT
Why do you add +0.5 to the difference?
Computer Guru
@Computer Guru, it's a common technique for rounding positive values. When the value gets truncated to an integer value, anything between 0.0 and 0.4999... before the addition gets truncated to 0, and between 0.5 and 0.9999... gets truncated to 1.
Mark Ransom
+3  A: 

I also recommend the tools offered by Boost. Either the mentioned Boost Timer, or hack something out of Boost.DateTime or there is new proposed library in the sandbox - Boost.Chrono: This last one will be a replacement for the Timer and will feature:

  • The C++0x Standard Library's time utilities, including:
    • Class template duration
    • Class template time_point
    • Clocks:
      • system_clock
      • monotonic_clock
      • high_resolution_clock
  • Class template timer, with typedefs:
    • system_timer
    • monotonic_timer
    • high_resolution_timer
  • Process clocks and timers:
    • process_clock, capturing real, user-CPU, and system-CPU times.
    • process_timer, capturing elapsed real, user-CPU, and system-CPU times.
    • run_timer, convenient reporting of |process_timer| results.
  • The C++0x Standard Library's compile-time rational arithmetic.

Here is the source of the feature list

Anonymous
thanks .. except I need it now, not when C++0x/1x comes out
hasen j
For now you can use the Boost Timer and then gracefully migrate to Chrono when it is reviewed/accepted.
Anonymous
+3  A: 

If you don't need the code to be portable to old unices, you can use clock_gettime(), which will give you the time in nanoseconds (if your processor supports that resolution). It's POSIX, but from 2001.

ebencooke
+1  A: 

clock() has a often a pretty lousy resolution. If you want to measure time at the millisecond level, one alternative is to use clock_gettime(), as explained in this question.

(Remember that you need to link with -lrt on Linux).

JesperE
+10  A: 

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 maximally 5 seconds. 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.

Johannes Schaub - litb
A: 

As an update,appears that on windows clock() measures wall clock time (with CLOCKS_PER_SEC precision)

 http://msdn.microsoft.com/en-us/library/4e2ess30(VS.71).aspx

while on Linux it measures cpu time across cores used by current process

http://www.manpagez.com/man/3/clock

and (it appears, and as noted by the original poster) actually with less precision than CLOCKS_PER_SEC, though maybe this depends on the specific version of Linux.

rogerdpack
A: 

I've written a Timer class based on CTT's answer. It can be used in the following way:

Timer timer = Timer();
timer.start();
/* perform task */
double duration = timer.stop();
timer.printTime(duration);

Here is its implementation:

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
using namespace std;

class Timer {
private:

    timeval startTime;

public:

    void start(){
        gettimeofday(&startTime, NULL);
    }

    double stop(){
        timeval endTime;
        long seconds, nseconds;
        double duration;

        gettimeofday(&endTime, NULL);

        seconds  = endTime.tv_sec  - startTime.tv_sec;
        nseconds = endTime.tv_usec - startTime.tv_usec;

        duration = seconds + nseconds/1000000.0;

        return duration;
    }

    static void printTime(double duration){
        printf("%5.6f seconds\n", duration);
    }
};
Chris Redford