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.

posted @   FredGrit  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 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
点击右上角即可分享
微信分享提示