5

I am currently using time from the ctime library. Is there any faster alternative?

time_t start_time, elapsed_time;

for(int i = 0; i < n; i++) {
    start_time = time(NULL);
    /// optimized code
    if(condition_met())
    {
       elapsed_time = time(NULL) - start_time;
    } else continue;
}

time(NULL) just isn't fast enough.

Sebi
  • 3,472
  • 13
  • 54
  • 93
  • 10
    How did you determine `time` isn't fast enough ? – cnicutar Aug 17 '12 at 10:45
  • 1
    Not in the standard library. Specific systems have specific ways to measure execution time, you need to specify what system/OS the code is intended for. – Lundin Aug 17 '12 at 10:45
  • 1
    I am looking for a faster alternative. It is not enough because it introduces an overhead(the method in which it is being used is called roughly 10mil times per second) – Sebi Aug 17 '12 at 10:46
  • I am currently on a windows(32bit) box. – Sebi Aug 17 '12 at 10:47
  • 4
    Why would you call it so often? What are you trying to do? Probably there is a better approach. – KillianDS Aug 17 '12 at 10:47
  • By 'fast', are you talking about the resolution? Are you always getting 0 for `elapsed_time`. – Skizz Aug 17 '12 at 10:49
  • On Linux x64, `gettimeofday` is a virtual syscall which is pretty fast. – Kerrek SB Aug 17 '12 at 10:50
  • 1
    It is a network generator. It generates networks based on a certain topology and then tries simulating traffic in a cluster. I'm using that function in order to determine a very basic performance metric. – Sebi Aug 17 '12 at 10:52

2 Answers2

8

You seem to want to only measure elapsed time (and aren't concerned with the absolute time). One of the fastest approaches of measuring elapsed time (if you are on x86) is to read the rdtsc counter. In mvsc++ this can be achieved by:

#include <intrin.h>
unsigned __int64 rdtsc(void)
{
    return __rdtsc();
}
cmh
  • 9,452
  • 4
  • 28
  • 40
  • 2
    Do note the caveats of using this method on multi-core/hyperthreaded systems as described in the linked wikipedia entry. For Windows systems the [recommended alternative](http://msdn.microsoft.com/en-us/library/ee417693%28VS.85%29.aspx) is to use `QueryPerformanceCounter` and `QueryPerformanceFrequency`. – Shawn Chin Aug 17 '12 at 10:57
  • 2
    But would you care to explain on how to use this to measure elapsed time ? – Neel Basu Aug 17 '12 at 10:59
  • One could also affinitize the thread using RDTSC to a specific CPU. – Alexey Frunze Aug 17 '12 at 11:06
2

I'm not sure, but I'm guessing that, given that it counts whole seconds, what you may be saying is that time(NULL) is not granular enough. In other words, you may be wanting to go down to milli, micro or nano seconds.

If that's the case take a look at this question

Community
  • 1
  • 1
Component 10
  • 9,649
  • 4
  • 42
  • 58