本文主要是介绍C++使用std::chrono来计算代码段所花费的时间,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C++获取程序段运行时间
- @[TOC](C++获取程序段运行时间)
- 使用std::chrono,代码如下:
- 结果
C++获取程序段运行时间
- @[TOC](C++获取程序段运行时间)
- 使用std::chrono,代码如下:
- 结果
使用std::chrono,代码如下:
//头文件
#include <iostream>
#include <chrono>
#include <string>
#include <thread>// 类定义class ScopeTimer {
public:using Duration = std::chrono::duration<float, std::milli>;using TimePoint = std::chrono::time_point<std::chrono::steady_clock, Duration>;public:ScopeTimer() = delete;ScopeTimer(const ScopeTimer&) = delete;ScopeTimer(const std::string& name) :name_(name), start_(std::chrono::steady_clock::now()), end_() {}~ScopeTimer() {end_ = std::chrono::steady_clock::now();std::cout << name_ << " take " << (end_ - start_).count() << " ms." << std::endl;}
private:std::string name_;TimePoint start_;TimePoint end_;
};// 测试
void Test1() {ScopeTimer st("I'm test1");std::this_thread::sleep_for(std::chrono::milliseconds(100));
}void Test2() {ScopeTimer st("I'm test2");std::this_thread::sleep_for(std::chrono::milliseconds(30));
}
int main(int argc, char* argv[])
{Test1();Test2();return 0;
}
结果
这篇关于C++使用std::chrono来计算代码段所花费的时间的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!