草庐IT

c++ - 任何运算符、函数调用和构造函数的通用持续时间计

coder 2024-02-22 原文

我使用模板化的 meter 函数(见下文)来测量函数的运行时间。 然后我也想将它用于构造函数。

据我所知,没有办法直接将类型作为函数参数传递。所以我想出了这个解决方法,将它仅作为模板参数传递(最小示例):

template <typename T, typename ... P>
auto meter(T t, P ... p) {
    auto t1 = high_resolution_clock::now();
    t(p...);
    auto t2 = high_resolution_clock::now();
    auto dif = t2-t1;   
    return duration_cast<microseconds>(dif);
}

template <typename T, typename ... P>
auto meter(P ... p) {
    auto t1 = high_resolution_clock::now();
    auto t = T(p...);
    auto t2 = high_resolution_clock::now();
    auto dif = t2-t1;   
    return duration_cast<microseconds>(dif);
}

int main() {
    auto d = meter(g, 1.0, 20.0); //meter the function call g(1.0, 20.0)
    std::cout << "Ellapsed time: " << d.count() << " microseconds\n";
    d = meter(complex_obj{2}); //meter () operator of complex_obj, assuming complex_obj{int} is trivial;
    std::cout << "Ellapsed time: " << d.count() << " microseconds\n";
    d = meter<complex_obj>(); //meter constructor complex_obj();
    std::cout << "Ellapsed time: " << d.count() << " microseconds\n";
}

尝试这个让我开始思考。是否有一种通用/一致的方法来重写它,以应用于任何类型的计算(不仅仅是构造函数,甚至可能是其他运算符,如 (obj1 < obj2)?我注意到,我已经(意外地)支持="">

抱歉,如果这个问题变得过于宽泛,我的主要问题是,是否有一种方法可以统一 meter 调用的语法,对于函数和构造函数都是一样的。

最佳答案

您可以将要测量的代码包装在 lambda 中(自 C++11 起):

#include <chrono>
#include <iostream>

template<class F>
auto meter(F&& f) {
  auto t1 = std::chrono::high_resolution_clock::now();
  f();//                                                <-- operator() of the lambda
  auto t2 = std::chrono::high_resolution_clock::now();
  auto dif = t2-t1;
  return std::chrono::duration_cast<std::chrono::microseconds>(dif);
}

void g(double x, double y) {
  std::cout << "g(" << x << ", " << y << ")\n";
}

int main() {
  double x = 1.0;
  auto d = meter([&] {
    // This comment is inside the *body* of the lambda.
    // Code of the {body} is executed upon `operator()`.
    g(x, 20.0);// note that you can use `x` here thanks to the capture-default `[&]`
  });
  std::cout << "time: " << d.count() << " ms\n";
}

关于c++ - 任何运算符、函数调用和构造函数的通用持续时间计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56752036/

有关c++ - 任何运算符、函数调用和构造函数的通用持续时间计的更多相关文章

  1. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  4. ruby - 触发器 ruby​​ 中 3 点范围运算符和 2 点范围运算符的区别 - 2

    请帮助我理解范围运算符...和..之间的区别,作为Ruby中使用的“触发器”。这是PragmaticProgrammersguidetoRuby中的一个示例:a=(11..20).collect{|i|(i%4==0)..(i%3==0)?i:nil}返回:[nil,12,nil,nil,nil,16,17,18,nil,20]还有:a=(11..20).collect{|i|(i%4==0)...(i%3==0)?i:nil}返回:[nil,12,13,14,15,16,17,18,nil,20] 最佳答案 触发器(又名f/f)是

  5. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  6. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  7. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  8. ruby-on-rails - RSpec:避免使用允许接收的任何实例 - 2

    我正在处理旧代码的一部分。beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)endRubocop错误如下:Avoidstubbingusing'allow_any_instance_of'我读到了RuboCop::RSpec:AnyInstance我试着像下面那样改变它。由此beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)end对此:let(:sport_

  9. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  10. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

随机推荐