簡體   English   中英

如何打印我的代碼的執行時間?

[英]How to print the execution time of my code?

我正在使用Visual Studio 2013,我需要找出我的代碼(C ++)的執行時間。 無論如何,有什么讓我這么做的?

這可能是答案之一:

對於Visual Studio :轉到“ Tools / Options / Projects and Solutions / VC++ Project Settings然后將“ Build Timing選項設置為“ yes ”。 之后,每個構建的時間將顯示在“輸出”窗口中。

對於C

    #include <time.h>
    int main(void) 
    {
       clock_t tStart = clock();
       /* Do your stuff here */
       printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
       return 0;
    }

對於C++

對於C++11

嘗試從<time.h>使用函數clock()

#include <time.h>
#include <iostream>
int main()
{
    clock_t clkStart;
    clock_t clkFinish;

    clkStart = clock();
    for(int i = 0; i < 10000000; i++)
        ;
    //other code
    clkFinish = clock();
    std::cout << clkFinish - clkStart;

    system("pause");
    return 0;
}

我用這樣的東西:

#include <chrono>
#include <thread>
#include <iostream>

class Timer
{
    // make things readable
    using clk = std::chrono::steady_clock;

    clk::time_point b; // begin
    clk::time_point e; // end

public:
    void clear() { b = e = clk::now(); }
    void start() { b = clk::now(); }
    void stop() { e = clk::now(); }

    friend std::ostream& operator<<(std::ostream& o, const Timer& timer)
    {
        return o << timer.secs();
    }

    // return time difference in seconds
    double secs() const
    {
        if(e <= b)
            return 0.0;
        auto d = std::chrono::duration_cast<std::chrono::microseconds>(e - b);
        return d.count() / 1000000.0;
    }
};

int main()
{
    Timer timer;

    timer.start();

    // do your stuff...
    for(int i = 0; i < 1000; ++i)
        std::this_thread::sleep_for(std::chrono::milliseconds(10));

    timer.stop();

    std::cout << "time: " << timer << " secs" << '\n';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM