使用clock()计时C程序出现时间值异常问题求助
问题原因与修复方案
问题根源
- 未初始化变量导致垃圾值:
solutionFound变量定义后未赋初始值,若循环中match()从未返回true,该变量会保留栈内存中的随机垃圾值。由于clock_t本质是整数类型(通常为unsigned long或long),垃圾值可能是极大正数甚至负数(溢出时),最终导致计算出的时间完全异常。 - 循环语法错误:
for循环条件部分末尾多了一个分号:for (int i = 1; i < maxLength; i++;),这会让循环体仅执行一次,甚至引发编译警告/错误,直接打乱程序执行逻辑。
修复方法
- 初始化计时变量:给
solutionFound赋初始值(比如0或与start相同的值),后续可通过判断初始值是否被修改,处理“未找到解”的场景。 - 修正循环语法:移除
i++后面多余的分号,保证循环正常迭代。 - 增加异常分支处理:输出计时结果前,先判断
solutionFound是否被更新,避免输出无效时间数据。
修正后的代码示例
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // 假设match()函数已正确定义 int match() { // 示例逻辑,可替换为实际代码 static int count = 0; return (++count == 5) ? 1 : 0; } int main() { int maxLength; printf("Enter max length: "); scanf("%d", &maxLength); clock_t start, solutionFound = 0, end; long double timeToFindSolution, timeToRun; start = clock(); // 修正循环末尾的多余分号 for (int i = 1; i < maxLength; i++) { // work... if(match()) { solutionFound = clock(); // 找到解后无需继续循环可直接退出 break; } } end = clock(); // 判断是否找到解,再输出对应结果 if (solutionFound != 0) { timeToFindSolution = ((long double) (solutionFound - start)) / CLOCKS_PER_SEC; printf("solution found in %Lf seconds\n", timeToFindSolution); } else { printf("no solution found during the loop\n"); } timeToRun = ((long double) (end - start)) / CLOCKS_PER_SEC; printf("total runtime: %Lf seconds\n", timeToRun); printf("start = %ld, foundPswd = %ld, end = %ld\n", (long)start, (long)solutionFound, (long)end); return 0; }
额外提示:如果找到解后不需要继续执行循环,建议在solutionFound = clock();后添加break;语句,避免无意义迭代,提升程序效率。
内容的提问来源于stack exchange,提问作者sunner
相关产品推荐
相关产品推荐

