简体   繁体   English

在 C++ 中为类函数计时

[英]Timing a class function in C++

A previous post, Timing in an elegant way in C , showed a neat method for profiling using a wrapper function.之前的一篇文章, 在 C 中以一种优雅的方式计时,展示了一种使用包装函数进行分析的简洁方法。 I am trying to use one of the profiler to profile my class functions.我正在尝试使用其中一个分析器来分析我的类函数。

#include <cmath>
#include <string>
#include <chrono>
#include <algorithm>
#include <iostream>

template<typename Duration = std::chrono::microseconds,
         typename F,
         typename ... Args>
typename Duration::rep profile(F&& fun,  Args&&... args) {
  const auto beg = std::chrono::high_resolution_clock::now();
  std::forward<F>(fun)(std::forward<Args>(args)...);
  const auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - beg).count();
}

The profiler works for a normal function, but I am struggling to pass a class function to the profiler.探查器适用于普通功能,但我正在努力将类函数传递给探查器。

#include "Profiler.h"

int main()
{
    Config projConfig = Config(projConfigDir);
    std::string imagePath = projConfig.GetTIFF();
    
    ImageVector images_vec = Image::LoadImagesVec(imagePath);
    Detector detector = Detector(&projConfig);

    auto time = profile<std::chrono::seconds>(&Detector::DetectImages, detector, images_vec);
    //detector.DetectImages(images_vec); // if ran without profiler
    std::string _detectTime("DetectImages time elapsed: " + std::to_string(time));
    Logger::Info(_detectTime.c_str());
}

I am unable to compile the code.我无法编译代码。 I got the following error message.我收到以下错误消息。

term does not evaluate to a function taking 2 arguments

Because I cannot pass pointer to a bounded function to the profiler, I tried passing in the function, the object instance to call the function and the function's arguments (not sure if this is the correct way).因为我无法将指向有界函数的指针传递给分析器,所以我尝试传入函数、调用函数的对象实例和函数的参数(不确定这是否是正确的方法)。 But I suspect that the profiler is not implemented to handle class methods.但我怀疑分析器没有实现来处理类方法。 If so, how should I modify the profiler so that it can accept class functions?如果是这样,我应该如何修改探查器以便它可以接受类函数?

You can use std::bind to create a callable object for invoking a class method on a class object.您可以使用std::bind创建一个可调用对象,以便在类对象上调用类方法。

Then you can pass this callable to your profile function as you would pass any function/lambda.然后,您可以将此可调用对象传递给您的profile函数,就像传递任何函数/lambda 一样。
Note that using std::bind supports also fixing one or more of the method parameters.请注意,使用std::bind还支持修复一个或多个方法参数。
Using std::placeholders (as you can see below) allows to specify them only when invoking the binded callable object.使用std::placeholders (如下所示)允许仅在调用绑定的可调用对象时指定它们。

See the example below:请参见下面的示例:

#include <chrono>
#include <iostream>
#include <functional>
#include <thread>
#include <string>

template<typename Duration = std::chrono::microseconds,
         typename F,
         typename ... Args>
    typename Duration::rep profile(F&& fun, Args&&... args) 
{
    const auto beg = std::chrono::high_resolution_clock::now();
    std::forward<F>(fun)(std::forward<Args>(args)...);
    const auto end = std::chrono::high_resolution_clock::now();
    return std::chrono::duration_cast<Duration>(end - beg).count();
}

struct MyClass
{
    void Run(std::string const & s, double d)
    {
        std::cout << "My id: " << id << ",  MyClass::Run(" << s << ", " << d << ")" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    int id{ 333 };
};

int main()
{
    MyClass c;

    // Run without profiling:
    c.Run("without", 2.3);

    // Run  with profiling:
    auto f = std::bind(&MyClass::Run, &c, std::placeholders::_1, std::placeholders::_2);
    auto time = profile<std::chrono::milliseconds>(f, "with", 23);
    std::cout << "time: " << time << std::endl;
    return 0;
}

Output:输出:

My id: 333,  MyClass::Run(without, 2.3)
My id: 333,  MyClass::Run(with, 23)
time: 109

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

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