测量C ++中函数的执行时间 [英] Measuring execution time of a function in C++

查看:135
本文介绍了测量C ++中函数的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道某个函数在我的C ++程序中在 Linux 上执行的时间。之后,我想做一个速度比较。我看到几个时间功能,但最终与这一增加。 Chrono:

I want to find out how much time a certain function takes in my C++ program to execute on Linux. Afterwards, I want to make a speed comparison . I saw several time function but ended up with this from boost. Chrono:

process_user_cpu_clock, captures user-CPU time spent by the current process

现在,我不清楚如果我使用上述函数,我会得到CPU花在那个函数上的唯一时间吗?

Now, I am not clear if I use the above function, will I get the only time which CPU spent on that function?

其次,我找不到任何使用上述函数的例子。任何一个请帮助我如何使用上述功能?

Secondly, I could not find any example of using the above function. Can any one please help me how to use the above function?

PS:现在,我使用 std :: chrono :: system_clock: :now()以秒为单位获取时间,但这会因为每次不同的CPU负载而产生不同的结果。

P.S: Right now , I am using std::chrono::system_clock::now() to get time in seconds but this gives me different results due to different CPU load every time.

推荐答案

这是一个非常容易使用的方法在C ++ 11。您必须使用< chrono> 标题

使用它:

#include <iostream>
#include <chrono>

using namespace std;
using namespace std::chrono;

void function()
{
    long long number = 0;

    for( long long i = 0; i != 2000000; ++i )
    {
       number += 5;
    }
}

int main()
{
    high_resolution_clock::time_point t1 = high_resolution_clock::now();
    function();
    high_resolution_clock::time_point t2 = high_resolution_clock::now();

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

    cout << duration;
    return 0;
}

这将测量函数的持续时间。

This will measure the duration of the function.

注意:始终不会得到相同的输出,因为计算机上运行的其他进程可能会减少或更多地使用机器的CPU。当你解决数学运算时,你的心意可以或多或少地集中,所以你将在不同的时间解决。在人类的心中,我们可以记住数学问题的解,虽然对于计算机来说,相同的过程总是新的东西,所以,正如我说的,它不需要总是得到相同的结果!

NOTE: It is not a requirement to get the same output always because the CPU of your machine can be less or more used by other processes running on your computer. As you would solve a math exercise, your mind can be more or less concentrated so you will solve that in different times. In the human mind, we can remember the solution of a math problem, though for a computer the same process will always be something new, so, as I Said, it is not required to get the same result always!

这篇关于测量C ++中函数的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆