写一个c++-计时的代码使用相对时间单位以秒为单位
以下是一个使用C++的chrono库实现的计时器代码,计时单位为秒:
#include <iostream>
#include <chrono>
int main()
{
auto start = std::chrono::high_resolution_clock::now();
// 执行需要计时的代码
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(end - start);
std::cout << "Time taken: " << duration.count() << " seconds" << std::endl;
return 0;
}
在这个代码中,我们使用了std::chrono::high_resolution_clock来获取当前时间,执行需要计时的代码后再次获取当前时间,计算两个时间点之间的差值,最后用duration_cast将差值转换为秒,并输出计时结果。
原文地址: https://www.cveoy.top/t/topic/gN5 著作权归作者所有。请勿转载和采集!