Measuring execution time of a function in C++

后端 未结 11 915
小鲜肉
小鲜肉 2020-11-22 12:59

I want to find out how much time a certain function takes in my C++ program to execute on Linux. Afterwards, I want to make a speed comparison . I saw sever

11条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 13:36

    • It is a very easy to use method in C++11.
    • We can use std::chrono::high_resolution_clock from header
    • We can write a method to print the method execution time in a much readable form.

    For example, to find the all the prime numbers between 1 and 100 million, it takes approximately 1 minute and 40 seconds. So the execution time get printed as:

    Execution Time: 1 Minutes, 40 Seconds, 715 MicroSeconds, 715000 NanoSeconds
    

    The code is here:

    #include 
    #include 
    
    using namespace std;
    using namespace std::chrono;
    
    typedef high_resolution_clock Clock;
    typedef Clock::time_point ClockTime;
    
    void findPrime(long n, string file);
    void printExecutionTime(ClockTime start_time, ClockTime end_time);
    
    int main()
    {
        long n = long(1E+8);  // N = 100 million
    
        ClockTime start_time = Clock::now();
    
        // Write all the prime numbers from 1 to N to the file "prime.txt"
        findPrime(n, "C:\\prime.txt"); 
    
        ClockTime end_time = Clock::now();
    
        printExecutionTime(start_time, end_time);
    }
    
    void printExecutionTime(ClockTime start_time, ClockTime end_time)
    {
        auto execution_time_ns = duration_cast(end_time - start_time).count();
        auto execution_time_ms = duration_cast(end_time - start_time).count();
        auto execution_time_sec = duration_cast(end_time - start_time).count();
        auto execution_time_min = duration_cast(end_time - start_time).count();
        auto execution_time_hour = duration_cast(end_time - start_time).count();
    
        cout << "\nExecution Time: ";
        if(execution_time_hour > 0)
        cout << "" << execution_time_hour << " Hours, ";
        if(execution_time_min > 0)
        cout << "" << execution_time_min % 60 << " Minutes, ";
        if(execution_time_sec > 0)
        cout << "" << execution_time_sec % 60 << " Seconds, ";
        if(execution_time_ms > 0)
        cout << "" << execution_time_ms % long(1E+3) << " MicroSeconds, ";
        if(execution_time_ns > 0)
        cout << "" << execution_time_ns % long(1E+6) << " NanoSeconds, ";
    }
    

提交回复
热议问题