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.
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.
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.
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);
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.
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();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With