要获取代码运行的时间,一个比较好的方式是使用chrono。
看例子,在两次获取时间的代码中间,休眠1s
#include <iostream>
#include <chrono>
#include <thread>
int main() {
using namespace std::literals::chrono_literals;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(1s);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> duration = end - start;
std::cout << duration.count() << "s" << std::endl;
std::cin.get();
}
输出大致为1秒:
1.00451s
再看forloop打印100次的时间:
#include <iostream>
#include <chrono>
#include <thread>
struct Timer {
std::chrono::time_point<std::chrono::steady_clock> start, end;
std::chrono::duration<float> duration;
Timer(){
start = std::chrono::high_resolution_clock::now();
}
~Timer() {
end = std::chrono::high_resolution_clock::now();
duration = end - start;
float ms = duration.count()*1000.0f;
std::cout << "Timer took " << ms << "ms" << std::endl;
}
};
void func() {
Timer timer;
for (int i = 0;i < 100;i++)
std::cout << "hello" << std::endl;
}
int main() {
func();
std::cin.get();
}
代码做了结构化调整,将相关功能都提取到一个结构中,然后在func函数中创建一个Timer,当func执行完毕,Timer自动析构。输出为:
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
Timer took 105.268ms
如果去掉std::cout << "hello" << std::endl; 语句的std::endl,再看执行时间:
lohelloTimer took 4.839ms