阅读量:0
- 计算程序运行时间
#include <iostream> #include <ctime> int main() { clock_t start, end; start = clock(); // 执行需要计时的代码 end = clock(); double duration = double(end - start) / CLOCKS_PER_SEC; std::cout << "程序运行时间:" << duration << "秒" << std::endl; return 0; }
- 计算函数执行时间
#include <iostream> #include <ctime> void func() { clock_t start, end; start = clock(); // 执行需要计时的代码 end = clock(); double duration = double(end - start) / CLOCKS_PER_SEC; std::cout << "函数执行时间:" << duration << "秒" << std::endl; } int main() { func(); return 0; }
- 计算两个操作之间的时间间隔
#include <iostream> #include <ctime> int main() { clock_t start, end; start = clock(); // 执行操作1 end = clock(); double duration1 = double(end - start) / CLOCKS_PER_SEC; start = clock(); // 执行操作2 end = clock(); double duration2 = double(end - start) / CLOCKS_PER_SEC; std::cout << "操作1执行时间:" << duration1 << "秒" << std::endl; std::cout << "操作2执行时间:" << duration2 << "秒" << std::endl; return 0; }