I’m trying to time my program using time.h. Code looks like below and I’m using gcc
to compile.
My problem is when I try to run this code (I’m using Visual Studio Code), start
and end
have approximately the same time, and solutionFound
is outrageously large for some reason (several orders of magnitude larger than end
, occasionally negative). Obviously these times are not right, but I don’t know why or how to fix it.
main.c
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main()
{
// some input/output using printf() and scanf() to get user options
clock_t start, solutionFound, end;
long double timeToFindSolution, timeToRun;
start = clock();
while(condition)
{
// work...
if(solutionFound()) { solutionFound = clock(); }
}
end = clock();
timeToFindSolution = ((long double) (solutionFound - start)) / CLOCKS_PER_SEC;
timeToRun = ((long double) (end - start)) / CLOCKS_PER_SEC;
printf("solution found in %es, took %es to runn", timeToFindSolution, timeToRun);
printf("start = %f, foundPswd = %f, end = %fn", (double)start, (double)solutionFound, (double)end);
return 0;
}
I tried putting end = clock()
inside my loop but that had no effect. I found a lot of questions on Stack Overflow about how to time a program but didn’t see anyone that had a similar problem.
I also tried making timeToFindSolution
and timeToRun
doubles instead of long doubles (not expecting the program to run very long anyway), still had the same problem.
4