C++代码执行时间测试

#include <iostream>
#include <chrono>
#define MAX_SIZE 100000
int main() {
    // 获取当前时间点
    auto start = std::chrono::high_resolution_clock::now();

    // 运行需要测试时间的程序
    int array[MAX_SIZE];
    for (int i = 0; i < MAX_SIZE; ++i) {
        array[i] = i + 1;
    }

    // 获取程序运行后的时间点
    auto end = std::chrono::high_resolution_clock::now();

    // 计算时间差
    std::chrono::duration<double> duration = end - start;

    // 将时间差转换为毫秒并输出
    std::cout << "程序运行时间为: " << duration.count() * 1000 << " 毫秒" << std::endl;

    return 0;
}

包装到函数

#include <chrono>
#include <iostream>
// 测量函数
template <typename Func, typename... Args> 
void measureTime(Func func, Args &&...args) {
    auto start = std::chrono::high_resolution_clock::now();
    func(std::forward<Args>(args)...);
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> duration = end - start;
    std::cout << "程序运行时间为: " << duration.count() * 1000 << " 毫秒" << std::endl;
}

int main() {
    auto test= []() {
        int array[100000];
        for (int i = 0; i < 100000; ++i) {
            array[i] = i;
        }
    };
    measureTime(test);
    return 0;
}

类的构造和析构 计算时间差

#include <chrono>
#include <iostream>

constexpr int max_num = 1000000;
int array[max_num];
class Timer {
  public:
    Timer() { now = std::chrono::steady_clock::now(); }
    ~Timer() { std::cout << std::chrono::duration<double>(std::chrono::steady_clock::now() - now) << std::endl; }

  private:
    std::chrono::time_point<std::chrono::steady_clock> now;
};

int main() {
    {
        Timer t;
        for (int i = 0; i < max_num; ++i) {
            array[i] = i;
        }
    }
}

包装到头文件

// Timer.h
#ifndef TIMER_H
#define TIMER_H
#include <chrono>
#include <iostream>
class Timer {
  public:
    Timer() { now = std::chrono::steady_clock::now(); }
    ~Timer() { std::cout << std::chrono::duration<double>(std::chrono::steady_clock::now() - now) << std::endl; }
  private:
    std::chrono::time_point<std::chrono::steady_clock> now;
};
#endif
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值