简体   繁体   English

测量操作块的时间

[英]measuring time of operation block

I'm using chrono library.我正在使用 chrono 库。 My code looks like:我的代码如下所示:

auto begin = chrono::high_resolution_clock::now();
// operations
auto end = chrono::high_resolution_clock::now();
auto elapsed = chrono::duration_cast<chrono::nanoseconds>(end - begin);
cout<<”time: „<<elapsed.count()<<endl;

And it always shows 0. What am I doing wrong?它总是显示0。我做错了什么?

To measure the difference between two times, save the difference in the appropriate object based on the precision you want:要测量两次之间的差异,请根据您想要的精度将差异保存在适当的 object 中:

std::chrono::duration<double, std::milli> fp_ms = end - start;//difference in milliseconds
std::chrono::duration<double, std::nano> fp_ns = end - start;//difference in nanoseconds

Then, you can convert this to seconds appropriately (or better yet, use the default in seconds duration<double> suggestion made by user chris in comments):然后,您可以适当地将其转换为秒(或者更好的是,使用用户 chris在评论中提出的默认秒duration<double>建议):

Live on Compiler Explorer实时编译器资源管理器

#include <iostream>
#include <chrono>
int main() {
    auto V = std::chrono::high_resolution_clock::now();
    for(int i = 0; i < 2000; i++)
        printf("%d ", i);
    printf("\n");
    auto Y = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> fp_s = Y - V;
    std::chrono::duration<double, std::milli> fp_ms = Y - V;
    std::chrono::duration<double, std::nano> fp_ns = Y - V;
    auto Zm = fp_ms.count()/1000.;
    auto Zn = fp_ns.count()/1000000000.;
    std::cout<<"Time from seconds in seconds is " << fp_s.count()<<std::endl;
    std::cout<<"Time from milliseconds in seconds is "<< Zm <<std::endl;
    std::cout<<"Time from nanoseconds in seconds is "<< Zn << std::endl;
//OP's method:
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(Y - V);
    std::cout<<"time: "<<elapsed.count()<<std::endl;
}

By the way, your method also works.顺便说一句,你的方法也有效。 See compiler explorer link above.请参阅上面的编译器资源管理器链接。

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

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