calculating execution time in c++

后端 未结 6 566
庸人自扰
庸人自扰 2020-12-22 19:26

I have written a c++ program , I want to know how to calculate the time taken for execution so I won\'t exceed the time limit.

#include

usin         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-22 20:00

    With C++11 for measuring the execution time of a piece of code, we can use the now() function:

    auto start = chrono::steady_clock::now();
    
    //  Insert the code that will be timed
    
    auto end = chrono::steady_clock::now();
    
    // Store the time difference between start and end
    auto diff = end - start;
    

    If you want to print the time difference between start and end in the above code, you could use:

    cout << chrono::duration  (diff).count() << " ms" << endl;
    

    If you prefer to use nanoseconds, you will use:

    cout << chrono::duration  (diff).count() << " ns" << endl;
    

    The value of the diff variable can be also truncated to an integer value, for example, if you want the result expressed as:

    diff_sec = chrono::duration_cast(diff);
    cout << diff_sec.count() << endl;
    

    For more info click here

提交回复
热议问题