60人参与 • 2025-03-17 • C/C++
<chrono>
库提供了高精度的时间测量功能。
#include <iostream> #include <chrono> int main() { auto start = std::chrono::high_resolution_clock::now(); // your code here // ... auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count(); std::cout << "elapsed time: " << duration << " ms\n"; return 0; }
<ctime>
库提供了基于系统时间的函数clock()。
#include <iostream> #include <ctime> int main() { clock_t start = clock(); //也可以double start = clock(); // your code here // ... clock_t end = clock(); double cpu_time_used = static_cast<double>(end - start) / clocks_per_sec; // /clocks_per_sec将结果转为以秒为单位 std::cout << "cpu time used: " << cpu_time_used << " s\n"; return 0; }
boost库提供了一个计时器模块,用于测量代码块的执行时间。
首先,你需要安装 boost库,并在项目中包含boost.timer头文件。
#include <boost/timer/timer.hpp> #include <iostream> int main() { boost::timer::auto_cpu_timer t; // 自动测量和打印执行时间 // your code here // ... return 0; }
这个函数返回从系统启动开始经过的毫秒数。gettickcount()
的精度在1到15毫秒之间,并且其值会在大约49.7天后回绕。
#include <windows.h> #include <iostream> int main() { dword start = gettickcount(); // ... 执行你的代码 ... dword end = gettickcount(); std::cout << "程序运行时间: " << (end - start) << " 毫秒" << std::endl; return 0; }
这两个函数提供了更高的精度,通常在微秒级别。
#include <windows.h> #include <iostream> int main() { large_integer start, end, freq; queryperformancefrequency(&freq); queryperformancecounter(&start); // ... 执行你的代码 ... queryperformancecounter(&end); double elapsedtime = (double)(end.quadpart - start.quadpart) / freq.quadpart * 1000.0; // 毫秒 std::cout << "程序运行时间: " << elapsedtime << " 毫秒" << std::endl; return 0; }
到此这篇关于c++记录程序运行时间的四种方法的文章就介绍到这了,更多相关c++程序运行时间内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论