precise time measurement

前端 未结 4 1999
甜味超标
甜味超标 2020-12-07 11:58

I\'m using time.h in C++ to measure the timing of a function.

clock_t t = clock();
someFunction();
printf(\"\\nTime taken: %.4fs\\n\", (float)(clock() - t)/         


        
4条回答
  •  再見小時候
    2020-12-07 12:28

    C++11 introduced the chrono API, you can use to get nanoseconds :

    auto begin = std::chrono::high_resolution_clock::now();
    
    // code to benchmark
    
    auto end = std::chrono::high_resolution_clock::now();
    std::cout << std::chrono::duration_cast(end-begin).count() << "ns" << std::endl;
    

    For a more relevant value it is good to run the function several times and compute the average :

    auto begin = std::chrono::high_resolution_clock::now();
    uint32_t iterations = 10000;
    for(uint32_t i = 0; i < iterations; ++i)
    {
        // code to benchmark
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast(end-begin).count();
    std::cout << duration << "ns total, average : " << duration / iterations << "ns." << std::endl;
    

    But remember the for loop and assigning begin and end var use some CPU time too.

提交回复
热议问题