Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast time function C/C++

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.

like image 526
Sebi Avatar asked Aug 17 '12 10:08

Sebi


People also ask

How does time () function work in C?

time() function in CThis function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.

What type of value is returned by the time () function in C?

Description. The C library function time_t time(time_t *seconds) returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. If seconds is not NULL, the return value is also stored in variable seconds.

What does time 0 do in C?

We can declare a variable to hold the current time from the system using: time_t now = time(0); time(0) can also be use in generating random values: #define SEED time(0); srand((unsigned int )SEED);

How do you use time in CPP?

To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program. There are four time-related types: clock_t, time_t, size_t, and tm. The types - clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer.


2 Answers

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();
}
like image 66
cmh Avatar answered Oct 07 '22 23:10

cmh


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

like image 27
Component 10 Avatar answered Oct 07 '22 22:10

Component 10