我正在使用 C 计算具有不同输入数据的程序的运行时间。 我运行该程序 100 次,想要找到平均运行时间。 为了找到平均值,我想将每个运行时间值存储到一个数组中,但是存储的值始终显示相同的数字。
我尝试将 float 类型更改为 long 和 double,但没有成功。 我添加了一条打印语句来显示这些值,它们是我想要的值,只有它们在插入数组后才会发生变化。
// 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
}
关于c - 尝试将程序的执行时间存储到数组中,但数组元素始终显示相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58071214/