cpp test for and while loop time cost respectively while std::chrono::high_resolution_clock
#include <chrono> #include <condition_variable> #include <ctime> #include <fstream> #include <future> #include <iomanip> #include <iostream> #include <map> #include <mutex> #include <sstream> #include <thread> #include <uuid/uuid.h> #include <vector> std::uint64_t for_cost = 0; std::uint64_t while_cost = 0; void test_for_duration(const std::uint64_t &len) { std::chrono::time_point<std::chrono::high_resolution_clock> start_time, end_time; start_time = std::chrono::high_resolution_clock::now(); std::uint64_t num; for (num = 0; num < len; num++) { } end_time = std::chrono::high_resolution_clock::now(); std::uint64_t cost = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count(); std::cout << "In " << __FUNCTION__ << "," << num << "," << cost << std::endl; for_cost += cost; } void test_while_duration(const std::uint64_t &len) { std::chrono::time_point<std::chrono::high_resolution_clock> start_time, end_time; start_time = std::chrono::high_resolution_clock::now(); std::uint64_t num = 0; while (++num < len) { } end_time = std::chrono::high_resolution_clock::now(); std::uint64_t cost = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count(); std::cout << "In " << __FUNCTION__ << "," << num << "," << cost << std::endl; while_cost += cost; } int main(int args, char **argv) { for (int i = 0; i < 10; i++) { test_for_duration(atoll(argv[1])); } for (int i = 0; i < 10; i++) { test_while_duration(atoll(argv[1])); } std::cout<<"For cost:"<<for_cost<<std::endl; std::cout<<"Whe cost:"<<while_cost<<std::endl; }
Compile
g++ -std=c++2a -I. *.cpp -o h1 -luuid -lpthread
Run
./h1 3000000000
The above snapshot has illustrated that the for loop cost less time than while loop totally.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2022-04-19 Compute the classic Fibonacci running times quantitatively via the third variable
2022-04-19 C++ numeric types max values via numeric_limits<T>::max()
2022-04-19 Original Fibonacci and optimized Fibonacci functions and use the third variable to log the recursion times quantitatively
2020-04-19 dynamic intercept and interpret all method calls via implementation IDynamicMetadataObjectProvider
2020-04-19 get caller member name,caller file path,caller line number via attributes
2020-04-19 try catch exception when