Skip to content

Instantly share code, notes, and snippets.

@penberg
Created December 30, 2020 13:06
Show Gist options
  • Save penberg/b50d393f49717393141f469df8246622 to your computer and use it in GitHub Desktop.
Save penberg/b50d393f49717393141f469df8246622 to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
static uint64_t timespec_to_ns(struct timespec *ts)
{
return ts->tv_sec * 1e9 + ts->tv_nsec;
}
static uint64_t time_diff(struct timespec *start, struct timespec *end)
{
uint64_t start_ns = timespec_to_ns(start);
uint64_t end_ns = timespec_to_ns(end);
assert(start_ns < end_ns);
return end_ns - start_ns;
}
int main(int argc, char *argv[])
{
struct timespec start, end;
if (clock_gettime(CLOCK_MONOTONIC, &start) < 0) {
assert(0);
}
int nr_iter = 10000000;
for (int i = 0; i < nr_iter; i++) {
void *p = malloc(64);
assert(p != NULL);
}
if (clock_gettime(CLOCK_MONOTONIC, &end) < 0) {
assert(0);
}
printf("%.2f ns/call\n", (double) time_diff(&start, &end) / (double) nr_iter);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment