Question

I want to get the running time of part of my code.

my C++ code is like:

...
time_t t1 = clock();
/*
Here is my core code.
*/
time_t t2 = clock();
cout <<"Running time: "<<  (1000.0 * (t2 - t1)) / CLOCKS_PER_SEC << "ms" << endl;
...

This code works well on my laptop.(Opensuse,g++ and clang++, Core i5).

But it does not work well on the cluster in the department. (Ubuntu, g++, amd Opteron and intel Xeon)

I always get some integer running time : like : 0ms or 10ms or 20ms.

What cause that ? Why? Thanks!

Was it helpful?

Solution

Clocks are not guaranteed to be exact down to ~10-44 seconds (Planck time), they often have a minimal resolution. The Linux man page implies this with:

The clock() function returns an approximation of processor time used by the program.

and so does the ISO standard C11 7.27.2.1 The clock function /3:

The clock function returns the implementation’s best approximation of ...

and in 7.27.1 Components of time /4:

The range and precision of times representable in clock_t and time_t are implementation-defined.

From your (admittedly limited) sample data, it looks like the minimum resolution of your cluster machines is on the order of 10ms.


In any case, you have several possibilities if you need a finer resolution.

  • First, find a (probably implementation-specific) means of timing things more accurately.

  • Second, don't do it once. Do it a thousand times in a tight loop and then just divide the time taken by 1000. That should roughly increase your resolution a thousand-fold.

  • Thirdly, think about the implication that your code only takes 50ms at the outside. Unless you have a pressing need to execute it more than twenty times a second (assuming you have no other code to run), it may not be an issue.

On that last point, think of things like "What's the longest a user will have to wait before they get annoyed?". The answer to that would vary but half a second might be fine in most situations.

Since 50ms code could run ten times over during that time, you may want to ignore it. You'd be better off concentrating on code that has a clearly larger impact.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top