简体   繁体   中英

measuring time of operation block

I'm using chrono library. 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?

To measure the difference between two times, save the difference in the appropriate object based on the precision you want:

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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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