-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
49 lines (42 loc) · 1.06 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "utils.h"
static float ticksPerNano;
// Returns time in "ticks". Use getTicksPerNano() to convert to nanoseconds.
unsigned long long inline preciseTime()
{
unsigned long lo, hi;
asm volatile (
"rdtsc;"
:"=a" (lo), "=d" (hi)
);
return ((unsigned long long) lo) | (((unsigned long long) hi) << 32);
}
void calibratePreciseTime() {
struct timespec ts;
unsigned long long start, diff;
unsigned long long mindiff = 0;
int i, ret;
ts.tv_sec = 0;
ts.tv_nsec = 1e8l;
for (i = 0; i < 10; i++) {
start = preciseTime();
ret = nanosleep(&ts, NULL);
diff = preciseTime() - start;
if (ret)
i--;
else if (mindiff == 0 || diff < mindiff)
mindiff = diff;
//printf("Diff: %lld\n", diff);
}
ticksPerNano = mindiff / (float)(ts.tv_sec * 1e9l + ts.tv_nsec);
}
float getTicksPerNano() {
if (ticksPerNano == 0) {
fprintf(stderr, "ERROR: call calibratePreciseTime() at the beginning of your program!\n");
exit(-1);
} else {
return ticksPerNano;
}
}