C语言循环每步计时异常:clock()函数返回值始终为0
问题原因
你的代码中单次外层循环的CPU耗时太短,小于clock()函数的精度阈值。clock()的精度由CLOCKS_PER_SEC定义,多数系统中这个值是1000,意味着最小可测量的时间单位是1毫秒。如果内层循环的操作耗时不足1ms,end - start的结果会是0,最终计算出的duration自然就是0.000000。
解决办法
1. 增加单次循环的工作量
直接提升内层循环的执行次数,让单次外层循环的总耗时超过clock()的精度范围:
#include <time.h> #include <stdio.h> #define number_of_elements 5 int main() { clock_t start, end; for(int i = 0; i < number_of_elements; i++) { start = clock(); // 大幅增加内层循环次数,确保耗时超过1ms for(int z = 1000000; z >= 0; z--) { // 保留你的处理逻辑 } for(int g = 0; g < 1000000; g++) { // 保留你的处理逻辑 } end = clock(); double duration = (double)(end - start) / CLOCKS_PER_SEC; printf("%d.step %f\n", i+1, duration); } return 0; }
2. 重复执行多次取平均
如果无法增加单次工作量,可以把单个i对应的操作重复执行N次,计算总耗时后除以N得到单次平均耗时,以此规避精度限制:
#include <time.h> #include <stdio.h> #define number_of_elements 5 #define REPEAT_COUNT 1000 // 重复次数可根据实际情况调整 int main() { clock_t start, end; for(int i = 0; i < number_of_elements; i++) { start = clock(); // 重复执行目标操作多次 for(int r = 0; r < REPEAT_COUNT; r++) { for(int z = /*something*/; z >= 0; z--) { // 你的处理逻辑 } for(int g = 0; g < /*something*/; g++) { // 你的处理逻辑 } } end = clock(); // 计算单次平均耗时 double total_duration = (double)(end - start) / CLOCKS_PER_SEC; double avg_duration = total_duration / REPEAT_COUNT; printf("%d.step %f\n", i+1, avg_duration); } return 0; }
3. 使用高精度计时API
如果需要微秒甚至纳秒级的精准计时,可使用平台特定的高精度函数:
- Linux/macOS:使用
clock_gettime,需包含<time.h>:
#include <time.h> #include <stdio.h> #define number_of_elements 5 int main() { struct timespec start, end; for(int i = 0; i < number_of_elements; i++) { clock_gettime(CLOCK_MONOTONIC, &start); for(int z = /*something*/; z >= 0; z--) { // 你的处理逻辑 } for(int g = 0; g < /*something*/; g++) { // 你的处理逻辑 } clock_gettime(CLOCK_MONOTONIC, &end); // 计算耗时,单位为秒 double duration = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1e9; printf("%d.step %lf\n", i+1, duration); } return 0; }
- Windows:使用
QueryPerformanceCounter,需包含<windows.h>:
#include <windows.h> #include <stdio.h> #define number_of_elements 5 int main() { LARGE_INTEGER start, end, freq; QueryPerformanceFrequency(&freq); for(int i = 0; i < number_of_elements; i++) { QueryPerformanceCounter(&start); for(int z = /*something*/; z >= 0; z--) { // 你的处理逻辑 } for(int g = 0; g < /*something*/; g++) { // 你的处理逻辑 } QueryPerformanceCounter(&end); // 计算耗时,单位为秒 double duration = (double)(end.QuadPart - start.QuadPart) / freq.QuadPart; printf("%d.step %lf\n", i+1, duration); } return 0; }
内容的提问来源于stack exchange,提问作者Andew Tayloe
相关产品推荐
相关产品推荐

