edit: I've figured it out. The 2nd algorithm was running so efficiently that the time wasn't even being recorded with an input < 100,000
I'm trying to measure how long a certain algorithm that I have implemented in a function takes to execute. I've included <time.h>
and I'm surrounding the function around time_t
variables. It works great for my first implementation, but not my second.
Do I need to close the clock stream (can't think of a better work)between uses? Kind of like how you close the Scanner
stream in a Java program. Here's my code in case I am not explaining it well.
switch(choice) {
case 1:
printf("Beginning prefixAverages1\n");
clock_t begin1 = clock();
int *a1 = prefixAverages1(input);
clock_t end1 = clock();
double time_spent1 = (double)(end1 - begin1) * 1000.0 / CLOCKS_PER_SEC;
free(a1);
printf("Algorithm took %f milliseconds to execute \n", time_spent1);
break;
case 2:
printf("Beginning prefixAverages2\n");
clock_t begin2 = clock();
int *a2 = prefixAverages2(input);
clock_t end2 = clock();
double time_spent2 = (double)(end2 - begin2) * 1000.0 / CLOCKS_PER_SEC;
free(a2);
printf("Algorithm took %f milliseconds to execute \n", time_spent2);
break;
default:
printf("Invalid input!");
break;
}
Time is displayed properly in my 1st case, but not in the second. I've tried doing some research but I can't find anything particular to my scenario.
When running case 1, depending on the input, I get a time between 600-1000 ms to run (which sounds about right). When I run case 2, regardless of the input, I get 00.000
Here are my functions if that helps:
int* prefixAverages1(int input) {
int x[input];
int *a = malloc(input*sizeof(*a));
srand(time(NULL));
for(int i = 0; i < input; i++) {
int sum = 0;
for(int j = 0; j < i; j++) {
int r = rand() % 100;
x[j] = r;
sum = sum + x[j];
}
a[i] = sum / (i+1);
}
return a;
}
int* prefixAverages2(int input) {
int sum = 0;
int x[input];
int *a = malloc(input*sizeof(*a));
srand(time(NULL));
for(int i = 0; i < input; i++) {
int r = rand() % 100;
x[i] = r;
sum = sum + x[i];
a[i] = sum / (i+1);
}
return a;
}