Skip to content

Instantly share code, notes, and snippets.

@jimfinnis
Created March 22, 2016 10:20
Show Gist options
  • Save jimfinnis/554cd51f5ac623659c90 to your computer and use it in GitHub Desktop.
Save jimfinnis/554cd51f5ac623659c90 to your computer and use it in GitHub Desktop.
Linux timer code
#include <stdio.h>
#include <time.h>
// calculate time in seconds between two timespecs
inline double time_diff(timespec start, timespec end)
{
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;
}
double t = temp.tv_sec;
double ns = temp.tv_nsec;
t += ns*1e-9;
return t;
}
class Timer {
private:
timespec starttime; //!< timespec of initialisation time
timespec marktime; //!< timespec of the mark
public:
Timer(){
clock_gettime(CLOCK_MONOTONIC,&starttime);
}
/// return the time since object construction in seconds
double timeSinceStart(){
struct timespec now;
clock_gettime(CLOCK_MONOTONIC,&now);
return time_diff(starttime,now);
}
/// set the mark time
void mark(){
clock_gettime(CLOCK_MONOTONIC,&marktime);
}
/// return the time since mark() in seconds
double timeSinceMark(){
struct timespec now;
clock_gettime(CLOCK_MONOTONIC,&now);
return time_diff(marktime,now);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment