I'm trying to have a loop execute for an exact time specified by executionTime
. I am using ctime
to get this timing, and I need it to be within a few milliseconds of accuracy (which I believe it is). Once that loop runs for the execution time specified, it should break.
My problem is for the execution time of 0.5, the result being printing is 1. Upon further testing it appears my program rounds up the execution time to the nearest integer. So for 4.5 executionTime
, the execution time being printed is 5.0000000. My code is below. I am not sure where this error is coming from.
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
float executionTime = 4.5;
int i;
float timeDifference = -1;
time_t t1;
time_t t2;
t1 = time(0);
for (i = 0; i < 1000000000; i++)
{
t2 = time(0);
timeDifference = difftime(t2, t1);
if (timeDifference >= executionTime)
{
break;
}
}
printf("time difference is: %f\n", timeDifference);
return 0;
}
NEW VERSION trying to use clock_gettime. This version has the issue of never breaking when execution time is reached for some reason inside the loop.
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define BILLION 1E9
int main()
{
float executionTime = 4.5;
int i;
float elapsedTime = -1;
struct timespec start;
struct timespec stop;
//Get starting time
clock_gettime(CLOCK_REALTIME, &start);
for (i = 0; i < 1000000000; i++)
{
//Get current time
clock_gettime(CLOCK_REALTIME, &stop);
elapsedTime = ((stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec)) / BILLION;
if (elapsedTime >= executionTime)
{
break;
}
}
printf("time difference is: %f\n", elapsedTime);
return 0;
}