Reputation: 539
I am using the following code to compute execution time in milli-secs.
struct timespec tp;
if (clock_gettime (CLOCK_REALTIME, &tp) == 0)
return ((tp.tv_sec * 1000000000) + tp.tv_nsec);
else
return ;
Can you please tell me whether this is correct? Let's name this function comptime_nano().
Now, I write the following code in main() to check execution times of following operations.
unsigned long int a, b, s1, s3;
a = (unsigned long int)(1) << 63;
b = (unsigned long int)(1) << 63;
btime = comptime_nano();
s1 = b >> 30;
atime = comptime_nano();
printf ("Time =%ld for %lu\n", (atime - btime), s1);
btime = comptime_nano();
s3 = a >> 1;
atime = comptime_nano();
printf ("Time =%ld for %lu\n", (atime - btime), s3);
To my surprise, the first operation takes about roughly 4 times more time than the second. Again, if I change the relative ordering of these operations, the respective timings change drastically.
Please comment...
Upvotes: 0
Views: 1462
Reputation: 44804
If your resolution isn't good enough, and you are running on an Intel PC, try using the realtime time-stamp counter (RDTSC). I found this code for using it on Umbutu:
#include<sys/time.h>
#include<time.h>
typedef unsigned long long ticks;
static __inline__ ticks getticks(void)
{
unsigned a, d;
asm("cpuid");
asm volatile("rdtsc" : "=a" (a), "=d" (d));
return (((ticks)a) | (((ticks)d) << 32));
}
Upvotes: 0
Reputation: 106549
clock_gettime
is not accurate enough for that kind of measurement. If you need to measure operations like that, do the operation several thousand (or several million times) in a loop before comparison. The two operations above should take the same amount of time but the second in your example code does not have the overhead of loading a
, b
, s1
, and s3
into the processor's cache.
Also, what's going on here?
struct timespec tp;
if (clock_gettime (CLOCK_REALTIME, &tp) == 0)
return ((tp.tv_sec * 1000000000) + tp.tv_nsec);
else
return ;
The first return is illegal if the function returns void
, and the second is illegal if it does not return void
....
EDIT: 1000000000
also overflows the range of int
.
Upvotes: 3