Easily measure elapsed time

前端 未结 26 2148
栀梦
栀梦 2020-11-22 04:13

I am trying to use time() to measure various points of my program.

What I don\'t understand is why the values in the before and after are the same? I understand thi

26条回答
  •  一向
    一向 (楼主)
    2020-11-22 05:03

    C++ std::chrono has a clear benefit of being cross-platform. However, it also introduces a significant overhead compared to POSIX clock_gettime(). On my Linux box all std::chrono::xxx_clock::now() flavors perform roughly the same:

    std::chrono::system_clock::now()
    std::chrono::steady_clock::now()
    std::chrono::high_resolution_clock::now()
    

    Though POSIX clock_gettime(CLOCK_MONOTONIC, &time) should be same as steady_clock::now() but it is more than x3 times faster!

    Here is my test, for completeness.

    #include 
    #include 
    #include 
    
    void print_timediff(const char* prefix, const struct timespec& start, const 
    struct timespec& end)
    {
        double milliseconds = end.tv_nsec >= start.tv_nsec
                            ? (end.tv_nsec - start.tv_nsec) / 1e6 + (end.tv_sec - start.tv_sec) * 1e3
                            : (start.tv_nsec - end.tv_nsec) / 1e6 + (end.tv_sec - start.tv_sec - 1) * 1e3;
        printf("%s: %lf milliseconds\n", prefix, milliseconds);
    }
    
    int main()
    {
        int i, n = 1000000;
        struct timespec start, end;
    
        // Test stopwatch
        clock_gettime(CLOCK_MONOTONIC, &start);
        for (i = 0; i < n; ++i) {
            struct timespec dummy;
            clock_gettime(CLOCK_MONOTONIC, &dummy);
        }
        clock_gettime(CLOCK_MONOTONIC, &end);
        print_timediff("clock_gettime", start, end);
    
        // Test chrono system_clock
        clock_gettime(CLOCK_MONOTONIC, &start);
        for (i = 0; i < n; ++i)
            auto dummy = std::chrono::system_clock::now();
        clock_gettime(CLOCK_MONOTONIC, &end);
        print_timediff("chrono::system_clock::now", start, end);
    
        // Test chrono steady_clock
        clock_gettime(CLOCK_MONOTONIC, &start);
        for (i = 0; i < n; ++i)
            auto dummy = std::chrono::steady_clock::now();
        clock_gettime(CLOCK_MONOTONIC, &end);
        print_timediff("chrono::steady_clock::now", start, end);
    
        // Test chrono high_resolution_clock
        clock_gettime(CLOCK_MONOTONIC, &start);
        for (i = 0; i < n; ++i)
            auto dummy = std::chrono::high_resolution_clock::now();
        clock_gettime(CLOCK_MONOTONIC, &end);
        print_timediff("chrono::high_resolution_clock::now", start, end);
    
        return 0;
    }
    

    And this is the output I get when compiled with gcc7.2 -O3:

    clock_gettime: 24.484926 milliseconds
    chrono::system_clock::now: 85.142108 milliseconds
    chrono::steady_clock::now: 87.295347 milliseconds
    chrono::high_resolution_clock::now: 84.437838 milliseconds
    

提交回复
热议问题