-
Notifications
You must be signed in to change notification settings - Fork 11
/
timer.cpp
33 lines (29 loc) · 941 Bytes
/
timer.cpp
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
#include <stdio.h>
#include <time.h>
#include "timer.h"
static struct timespec t[8];
static int timespec_subtract(struct timespec* result, struct timespec *x, struct timespec *y) {
if (x->tv_nsec < y->tv_nsec) {
int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
y->tv_nsec -= 1000000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_nsec - y->tv_nsec > 1000000000) {
int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
y->tv_nsec += 1000000000 * nsec;
y->tv_sec -= nsec;
}
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_nsec = x->tv_nsec - y->tv_nsec;
return x->tv_sec < y->tv_sec;
}
void timer_start(int id) {
clock_gettime(CLOCK_MONOTONIC, &t[id]);
}
double timer_end(int id) {
struct timespec x, y;
clock_gettime(CLOCK_MONOTONIC, &x);
timespec_subtract(&y, &x, &t[id]);
double elapsed = y.tv_sec + y.tv_nsec / 1e9;
return elapsed;
}