首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C++中测量函数的执行时间

在C++中测量函数的执行时间
EN

Stack Overflow用户
提问于 2014-03-14 02:23:31
回答 12查看 261.1K关注 0票数 193

我想知道某个函数在我的C++程序中执行需要多长时间

Linux

..。然后,我想做一个速度比较。我看到了几个时间函数,但最终在boost中得到了这个。计时器:

代码语言:javascript
复制
process_user_cpu_clock, captures user-CPU time spent by the current process

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

其次,我找不到任何使用上述函数的示例。有没有人可以教我如何使用上面的功能?

附言:现在,我正在使用std::chrono::system_clock::now()

来获取以秒为单位的时间,但由于每次CPU负载不同,这会给出不同的结果。

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2014-03-14 02:30:15

这是一个在C++11中非常容易使用的方法。std::chrono::high_resolution_clock发件人标头。

像这样使用它:

代码语言:javascript
复制
#include 

/* Only needed for the sake of this example. */
#include 
#include 
    
void long_operation()
{
    /* Simulating a long, heavy operation. */

    using namespace std::chrono_literals;
    std::this_thread::sleep_for(150ms);
}

int main()
{
    using std::chrono::high_resolution_clock;
    using std::chrono::duration_cast;
    using std::chrono::duration;
    using std::chrono::milliseconds;

    auto t1 = high_resolution_clock::now();
    long_operation();
    auto t2 = high_resolution_clock::now();

    /* Getting number of milliseconds as an integer. */
    auto ms_int = duration_cast(t2 - t1);

    /* Getting number of milliseconds as a double. */
    duration ms_double = t2 - t1;

    std::cout << ms_int.count() << "ms\n";
    std::cout << ms_double.count() << "ms";
    return 0;
}

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

可能的输出:

代码语言:javascript
复制
150ms
150.068ms

工作示例:

https://godbolt.org/z/oe5cMd

票数 364
EN

Stack Overflow用户

发布于 2015-11-25 01:49:36

下面是一个函数,它将测量作为参数传递的任何函数的执行时间:

代码语言:javascript
复制
#include 
#include 

typedef std::chrono::high_resolution_clock::time_point TimeVar;

#define duration(a) std::chrono::duration_cast(a).count()
#define timeNow() std::chrono::high_resolution_clock::now()

template
double funcTime(F func, Args&&... args){
    TimeVar t1=timeNow();
    func(std::forward(args)...);
    return duration(timeNow()-t1);
}

示例用法:

代码语言:javascript
复制
#include 
#include 

typedef std::string String;

//first test function doing something
int countCharInString(String s, char delim){
    int count=0;
    String::size_type pos = s.find_first_of(delim);
    while ((pos = s.find_first_of(delim, pos)) != String::npos){
        count++;pos++;
    }
    return count;
}

//second test function doing the same thing in different way
int countWithAlgorithm(String s, char delim){
    return std::count(s.begin(),s.end(),delim);
}


int main(){
    std::cout<<"norm: "<
代码语言:javascript
复制
norm: 15555
algo: 2976
票数 26
EN

Stack Overflow用户

发布于 2018-11-27 19:18:47

在Scott Meyer的书中,我发现了一个通用通用lambda表达式的例子,它可以用来测量函数的执行时间。(C++14)

代码语言:javascript
复制
auto timeFuncInvocation = 
    [](auto&& func, auto&&... params) {
        // get time before function invocation
        const auto& start = std::chrono::high_resolution_clock::now();
        // function invocation using perfect forwarding
        std::forward(func)(std::forward(params)...);
        // get time after function invocation
        const auto& stop = std::chrono::high_resolution_clock::now();
        return stop - start;
     };

问题是,您只测量一次执行,因此结果可能会非常不同。要获得可靠的结果,您应该测量大量的执行。根据Andrei Alexandrescu在code::dive 2015大会上的演讲-编写快速代码I:

测量时间: tm =t+ tq + tn +t0

其中:

tm -测量(观察)时间

T-感兴趣的实际时间

tq -量化噪声相加的时间

tn -由各种噪声源添加的时间

终止开销时间(测量、循环、调用函数)

根据他在讲座后面所说的,你应该将这些大量执行中的最小数量作为你的结果。我鼓励你去看看他的演讲,他在演讲中解释了原因。

还有一个来自google的非常好的库-

https://github.com/google/benchmark

..。这个库使用起来非常简单,而且功能非常强大。你可以在youtube上查看钱德勒·卡鲁斯的一些演讲,他正在实践中使用这个图书馆。例如CppCon 2017:钱德勒·卡鲁斯“更快无处可去”;

示例用法:

代码语言:javascript
复制
#include 
#include 
#include 
auto timeFuncInvocation = 
    [](auto&& func, auto&&... params) {
        // get time before function invocation
        const auto& start = high_resolution_clock::now();
        // function invocation using perfect forwarding
        for(auto i = 0; i < 100000/*largeNumber*/; ++i) {
            std::forward(func)(std::forward(params)...);
        }
        // get time after function invocation
        const auto& stop = high_resolution_clock::now();
        return (stop - start)/100000/*largeNumber*/;
     };

void f(std::vector& vec) {
    vec.push_back(1);
}

void f2(std::vector& vec) {
    vec.emplace_back(1);
}
int main()
{
    std::vector vec;
    std::vector vec2;
    std::cout << timeFuncInvocation(f, vec).count() << std::endl;
    std::cout << timeFuncInvocation(f2, vec2).count() << std::endl;
    std::vector vec3;
    vec3.reserve(100000);
    std::vector vec4;
    vec4.reserve(100000);
    std::cout << timeFuncInvocation(f, vec3).count() << std::endl;
    std::cout << timeFuncInvocation(f2, vec4).count() << std::endl;
    return 0;
}

编辑:当然,你总是需要记住,你的编译器可以优化某些东西,也可以不优化。像perf这样的工具在这种情况下很有用。

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22387586

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档