Skip to content

Instantly share code, notes, and snippets.

@Pocketkid2
Last active August 8, 2022 21:07
Show Gist options
  • Save Pocketkid2/90f7135046b6c0ba22ff053cada0390b to your computer and use it in GitHub Desktop.
Save Pocketkid2/90f7135046b6c0ba22ff053cada0390b to your computer and use it in GitHub Desktop.
Barebones library in C for timing things (uses POSIX time definition for counting elapsed seconds and milliseconds)
#include "stopwatch.h"
#include <sys/time.h>
#include <stdlib.h>
struct stop_watch {
struct timeval start;
struct timeval end;
};
Stopwatch stopwatch_create() {
return calloc(1, sizeof(struct stop_watch));
}
void stopwatch_start(Stopwatch s) {
gettimeofday(&(s->start), NULL);
}
void stopwatch_stop(Stopwatch s) {
gettimeofday(&(s->end), NULL);
}
long stopwatch_seconds(Stopwatch s) {
return s->end.tv_sec - s->start.tv_sec;
}
long stopwatch_microseconds(Stopwatch s) {
return s->end.tv_usec - s->start.tv_usec;
}
#ifndef STOPWATCH_H
#define STOPWATCH_H
// Define the Stopwatch as the object (pointer to struct)
struct stop_watch;
typedef struct stop_watch* Stopwatch;
// Returns a newly allocated Stopwatch object
Stopwatch stopwatch_create();
// Triggers the Stopwatch object to start or stop
void stopwatch_start(Stopwatch s);
void stopwatch_stop(Stopwatch s);
// Grab the number of seconds or microseconds that have elapsed on this Stopwatch
// WARNING: if stopwatch_start() and stopwatch_stop() are not both called in that order, behavior is not guaranteed
long stopwatch_seconds(Stopwatch s);
long stopwatch_microseconds(Stopwatch s);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment