New Linux Timing Code

silver and white round analog watch

For some time, I had a problem with my old Linux timing code. The units hr_time.h/c had to have the includes arranged in the right order and some flags set for it to compile. Plus it never seemed right having to do this in hr_time.h

#include <linux/time.h>
#define __timespec_defined 1
#define __itimerspec_defined 1
#define __timeval_defined 1

But today I found some better code on this SolarianProgrammer website and I’m always happy to give credit where it’s due. I’ve witched to using C17 which clang on Ubuntu (clang 14) and Raspberry Pi (clang 11) both seem to accept.

So now my hr_time.h looks like this:

hr_time.h

#pragma once
#include <stdlib.h>
#include <time.h>

void startTimer();
void stopTimer();
double diff();

hr_time.c

#include "hr_time.h"
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

struct timespec start;
struct timespec end;

void startTimer() {
	if (timespec_get(&start, TIME_UTC) != TIME_UTC) {
		printf("Error in calling timespec_get\n");
		exit(EXIT_FAILURE);
	}
};

void stopTimer() {
	if (timespec_get(&end, TIME_UTC) != TIME_UTC) {
		printf("Error in calling timespec_get\n");
		exit(EXIT_FAILURE);
	}
};

double diff()
{
	return  (double)(end.tv_sec - start.tv_sec) + 
			((double)(end.tv_nsec - start.tv_nsec) / 1000000000L);
}

I’m only ever using one timer, if you want to modify this to pass in a timer in the startTimer and stopTimer then it’s easy enough.

(Visited 19 times, 1 visits today)