66 lines
1.6 KiB
C
66 lines
1.6 KiB
C
#include <stdio.h>
|
|
#include <stdint.h>
|
|
#include <time.h>
|
|
#include <math.h>
|
|
#include "x86intrin.h"
|
|
|
|
struct rolling_stddev
|
|
{
|
|
uint64_t sum, count;
|
|
float mean, m2;
|
|
};
|
|
|
|
void roll(struct rolling_stddev *r, uint64_t value)
|
|
{
|
|
r->count++;
|
|
r->sum += value;
|
|
float d = value-r->mean;
|
|
r->mean += d/r->count;
|
|
r->m2 += d*(value-r->mean);
|
|
}
|
|
|
|
float dev(struct rolling_stddev *r)
|
|
{
|
|
return (r->m2/(r->count-1));
|
|
}
|
|
|
|
void test_clock(const char *name, clockid_t clockid)
|
|
{
|
|
struct rolling_stddev d = { 0 };
|
|
struct timespec ts, tp, te;
|
|
clock_gettime(clockid, &ts);
|
|
te = ts;
|
|
for (int i = 0; i < 100000000; i++)
|
|
{
|
|
clock_gettime(clockid, &tp);
|
|
uint64_t cur = ((tp.tv_sec-te.tv_sec)*1000000000 + (tp.tv_nsec-te.tv_nsec));
|
|
roll(&d, cur);
|
|
te = tp;
|
|
}
|
|
printf("%s: %lu ns, stddev %.2f ns\n", name, (te.tv_sec-ts.tv_sec)*10 + (te.tv_nsec-ts.tv_nsec)/100000000, sqrt(dev(&d)));
|
|
}
|
|
|
|
void test_rdtsc()
|
|
{
|
|
struct timespec ts, te;
|
|
clock_gettime(CLOCK_MONOTONIC, &ts);
|
|
uint64_t s = __rdtsc(), e;
|
|
for (int i = 0; i < 100000000; i++)
|
|
{
|
|
e = __rdtsc();
|
|
}
|
|
clock_gettime(CLOCK_MONOTONIC, &te);
|
|
printf("RDTSC: %lu ns\n", (te.tv_sec-ts.tv_sec)*10 + (te.tv_nsec-ts.tv_nsec)/100000000);
|
|
}
|
|
|
|
int main(int narg, char **args)
|
|
{
|
|
test_rdtsc();
|
|
test_clock("CLOCK_MONOTONIC_RAW", CLOCK_MONOTONIC_RAW);
|
|
test_clock("CLOCK_MONOTONIC", CLOCK_MONOTONIC);
|
|
test_clock("CLOCK_MONOTONIC_COARSE", CLOCK_MONOTONIC_COARSE);
|
|
test_clock("CLOCK_REALTIME", CLOCK_REALTIME);
|
|
test_clock("CLOCK_REALTIME_COARSE", CLOCK_REALTIME_COARSE);
|
|
return 0;
|
|
}
|