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

标签 c arrays time

我正在使用 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/

相关文章:

c++ - 如何通过最小增量(或接近它)改变 float ?

javascript - 从一组日期中获取每周和每月数据的最佳方法是什么?

c - 尝试将数组写入文件时检测到堆栈粉碎错误

javascript - Javascript 中的防欺骗时间

Php 时钟 2 小时后退

python - 在python中执行linux时间命令

c - 使用 sscanf 读取可选数字

c - 尝试将随机生成的 float 存储在数组中。但无法理解为什么数组采用垃圾值

c - 结构中的默认值

arrays - 为什么不使用 .map 从 stringArray 中删除最后一个句号