简体   繁体   English

测量C ++中函数调用的执行时间

[英]Measure the execution time of a function call in C++

How can I measure the execution time of a line of code in C++ in Windows . 如何在Windows中使用C++测量一行代码的执行时间。 I am inserting about 1,00,000 records boost::multi_index_container as follows: 我正在插入约1,00,000条记录boost::multi_index_container ,如下所示:

while(...) //read a single record from a csv file until EOF
{
    ...
    while(...) // split the record into components based on delimiter
    {
        ...
    }
    //insert into boost::multi_index_container
} 

I need to find the time required to insert all the records, but without the execution time of loops. 我需要找到插入所有记录所需的时间,但是没有循环的执行时间。 Starting a timer or anything just before insert function and calculating the elapsed time just after the function call gives 0 nanoseconds as the result. 在插入函数之前启动timer或任何其他操作,并在函数调用之后立即计算经过的时间,结果为0 nanoseconds So I cannot calculate the time by summing up the individual times. 因此,我无法通过汇总各个时间来计算时间。 What is the solution? 解决办法是什么?

在Windows上,您可以使用QueryPerformanceCounter获得准确的测量结果。

possible duplicate of How to calculate a time difference in C++ . C ++如何计算时差的可能重复项。 There are many ways to do this. 有很多方法可以做到这一点。 One that I like uses chrono. 我喜欢的一款使用chrono。

   #include <iostream>
   #include <chrono>

   using namespace std;
   using namespace std::chrono;



   int main()
  {
    high_resolution_clock::time_point t1 = high_resolution_clock::now();
    //your code here
    high_resolution_clock::time_point t2 = high_resolution_clock::now();

    auto duration = duration_cast<microseconds>( t2 - t1 ).count();

    cout << duration;
    return 0;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM