C语言 尝试将程序的执行时间存储到数组中,但数组元素始终显示相同的值



我正在使用C计算具有不同输入数据的程序的运行时间。 我正在运行该程序 100 次,并想找到平均运行时间。 为了找到平均值,我想将每个运行时间值存储到一个数组中,但是存储的值始终显示相同的数字。

我尝试将浮点类型更改为长整型和双倍型,但没有奏效。 我添加了一个 print 语句来显示值,它们是我想要的值,只有它们在插入数组后才会更改。

// C programming
int main(){
clock_t t;
int n, m = 0;
int arr_time[100]; // also tried changing the array type from int to float
int repeat, repeat_times = 1000;
for(n=1;n<100;++n)
{
t = clock();
for (repeat=0;repeat<repeat_times; ++repeat)
{
some_function();
}
t = clock()-t;
printf("%f", ((float)t)/CLOCKS_PER_SEC/repeat_times); // to check the values to be stored
arr_time[m] = ((float)t)/CLOCKS_PER_SEC/repeat_times; // values stored are not the same as previous line though
m+=1;
printf("It took %f seconds to run some_function(%d)n",
((float)t)/CLOCKS_PER_SEC/repeat_times,n);
}
int sum = 0;
for (n=1;n<100;++n)
{
sum += arr_time[n];
}
for (n=0;n<10;n++)
{
printf("(%f)n", arr[n]); // checking which values are stored into the array
}
printf("(%f)n", sum);
int average = ((float)sum)/99;
printf("The average time in seconds to run some_function is (%f)n", average);
return 0;
}

如何将时间值存储到数组中?

//...
arr_time[m] = ((float)t)/CLOCKS_PER_SEC/repeat_times;
//you can store them here where arr[] is float    
arr[n] = arr_time[m]
//
for (n=0;n<10;n++)
{
// or use arr_time[] and not arr[] because you are not using arr[] in your program
printf("(%f)n", arr_time[n]); // checking which values are stored into the array
}

最新更新