I needed to make a timer to profile small programs a while back. My use wasn't for a major project or mission critical code or anything even remotely close to that, just for personal learning purposes.
As I reviewed my old timer I found I was using clock
which measures cpu time. Now being aware of the difference between wall time and cpu time, I made this timer using clock_gettime
and was hoping for help finding any mistakes or possible improvements that could be made. Thanks.
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#define NANO 1000000000
int main(int argc, char *argv[])
{
struct timespec start;
struct timespec stop;
clock_gettime(CLOCK_REALTIME, &start);
double start_time = ((float) start.tv_sec) +
((float) start.tv_nsec) / NANO;
printf("%.4f\n", start_time);
sleep(3);
for (int i=1; i < 10000; i++) {
for (int j=i; j < 10000; j++) {
int l = j % i;
}
}
clock_gettime(CLOCK_REALTIME, &stop);
double stop_time = ((float) stop.tv_sec) +
((float) stop.tv_nsec) / NANO;
printf("%.4f\n", stop_time - start_time);
return 0;
}