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 @ 2023-04-19 23:42  FredGrit  阅读(8)  评论(0编辑  收藏  举报