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

C++中如何实现类似MATLAB tic/toc功能记录代码段运行时间并存入数组

C++等效实现方案

C++ 可以通过标准库的 <chrono> 头文件实现和 MATLAB tic/toc 完全对应的计时逻辑,无需引入第三方依赖,兼容所有主流编译器。

完整可运行示例

#include <iostream>
#include <chrono>
#include <vector>

// 模拟MATLAB tic功能,返回当前时间点作为toc的输入参数
auto tic() {
    return std::chrono::high_resolution_clock::now();
}

// 模拟MATLAB toc功能,输入tic返回的时间点,返回间隔耗时(默认单位为秒,和MATLAB toc默认单位对齐)
double toc(decltype(tic()) start) {
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;
    return diff.count();
}

int main() {
    const int n = 10; // 对应MATLAB代码里的循环次数n
    // 二维数组结构和MATLAB的array完全对应:第一维存2段代码的计时,第二维存n次运行的单次耗时
    std::vector<std::vector<double>> time_array(2, std::vector<double>(n));

    for (int i = 0; i < n; ++i) {
        // 第一段代码计时
        auto start = tic();
        // 此处替换为你需要运行的第一段业务代码
        for (int j = 0; j < 1000000; ++j); // 示例占位代码
        time_array[0][i] = toc(start);

        // 第二段代码计时
        start = tic();
        // 此处替换为你需要运行的第二段业务代码
        for (int j = 0; j < 2000000; ++j); // 示例占位代码
        time_array[1][i] = toc(start);
    }

    // 测试输出,你可以直接使用time_array做后续计算
    std::cout << "第一段代码各次运行耗时:" << std::endl;
    for (double t : time_array[0]) {
        std::cout << t << "s ";
    }
    std::cout << "\n第二段代码各次运行耗时:" << std::endl;
    for (double t : time_array[1]) {
        std::cout << t << "s ";
    }

    return 0;
}

补充说明

  • 如果需要其他单位的耗时,可以修改toc函数的duration模板参数:
    • 毫秒单位:替换为std::chrono::duration<double, std::milli>
    • 微秒单位:替换为std::chrono::duration<double, std::micro>
  • 存储耗时的容器如果需要固定长度,可以替换为原生数组或std::array,读写逻辑完全一致
  • 如果你使用C++11之前的标准,也可以用系统API实现计时:Windows下用QueryPerformanceCounter,Linux下用clock_gettime,优先推荐标准库实现,跨平台兼容性更好

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:42:00