如何打印我的代码的执行时间?

时间:2015-08-09 14:13:13

标签: c++ visual-studio visual-studio-2013

我正在使用visual studio 2013,我需要找出我的代码(C ++)的执行时间。反正有没有让我这样做?

3 个答案:

答案 0 :(得分:2)

这可能是可能的答案之一:

对于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

答案 1 :(得分:0)

尝试使用clock()中的函数<time.h>

#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;
}

答案 2 :(得分: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';
}