You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++使用chrono、clock计算函数执行时间结果恒为0求助

问题核心原因

你两处计时代码都存在单位换算错误,加上测试用例规模过小,才会输出0ms:

  • chrono方案错误:你将时间差转为nanoseconds(纳秒)后直接输出count值并标注为ms,1ms=1000000纳秒,未做单位转换的情况下,哪怕实际跑了数百纳秒,输出的数值远小于1,直接当作ms展示自然显示0
  • clock()方案错误:clock()返回的是程序运行的时钟滴答数,需要除以CLOCKS_PER_SEC得到秒级结果,乘以1000才是毫秒,你直接用差值输出等于没有做单位转换

正确计时实现代码

1. chrono库正确实现

void primsCall(){
    Prims prm(vec, adjMatrix);
    auto start = std::chrono::high_resolution_clock::now();
    prm.formMST(vec, adjMatrix);
    auto stop = std::chrono::high_resolution_clock::now();
    // 方式1:直接转换为毫秒级duration
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
    // 方式2:保留更高精度,纳秒转毫秒
    // double duration_ms = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start).count() / 1e6;
    cout<<"Prim's Algorithm MST: (total cost: "<<prm.mstCost<<"; runtime: "<<duration.count()<< "ms)"<<endl;
    for(string entry : prm.path){
        cout<<entry<<endl;
    }
    return;
}

2. clock()函数正确实现

void kruskalSCall(){
    cout<<endl<<endl;
    Kruskal ksk(vec, adjMatrix);
    clock_t start, end;
    start = clock();
    ksk.formMST(vec);
    end = clock();
    // 时钟滴答数转毫秒
    double runtime = (double)(end - start) / CLOCKS_PER_SEC * 1000;
    cout<<"Kruskal's Algorithm MST: (total cost: "<<ksk.kMstCost<<"; runtime: "<<runtime<< "ms)"<<endl;
    for(string entry : ksk.kPath){
        cout<<entry<<endl;
    }
    return;
}

短耗时函数测量方案

如果调整单位后输出仍为0,说明单次函数执行时间低于系统计时器精度(Windows下通常为10-15ms,Linux下约1ms),可采用多次循环取平均的方案:

int run_times = 10000;
long long total_cost = 0;
auto start = std::chrono::high_resolution_clock::now();
for(int i=0; i<run_times; i++){
    prm.formMST(vec, adjMatrix);
    total_cost += prm.mstCost; // 避免编译器判定循环无副作用优化掉
}
auto stop = std::chrono::high_resolution_clock::now();
double avg_duration_ms = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start).count() / 1e6 / run_times;
cout << "总执行次数:" << run_times << " 累计MST成本:" << total_cost << " 单次平均执行时间:" << avg_duration_ms << "ms" << endl;

注意:循环测量时建议消耗函数的输出结果,避免编译器直接优化掉循环逻辑,导致计时结果异常。

内容的提问来源于stack exchange,提问作者Suraj Mate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:06:02