Skip to content

Instantly share code, notes, and snippets.

@ray1422
Last active May 6, 2021 09:59
Show Gist options
  • Save ray1422/733b9ea2eddb5397555462c32b608730 to your computer and use it in GitHub Desktop.
Save ray1422/733b9ea2eddb5397555462c32b608730 to your computer and use it in GitHub Desktop.
Timer Macro for C
#pragma once
#include <string.h>
#include <sys/time.h>
#include <time.h>
inline static struct timespec diff(struct timespec start, struct timespec end) {
struct timespec temp;
if ((end.tv_nsec - start.tv_nsec) < 0) {
temp.tv_sec = end.tv_sec - start.tv_sec - 1;
temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec - start.tv_sec;
temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
return temp;
}
#define TIMER(v_double_var_assign, XXX) \
do { \
struct timespec start, end; \
double time_used; \
clock_gettime(CLOCK_MONOTONIC, &start); \
XXX; \
clock_gettime(CLOCK_MONOTONIC, &end); \
struct timespec temp = diff(start, end); \
v_double_var_assign = time_used = \
temp.tv_sec + (double)temp.tv_nsec / 1000000000.0; \
} while (0)
/*
usages:
TIMER(var_to_catch_time_sec, {
// operations here.
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment