codex
codex

Reputation: 90

How to print the execution time of my code?

I am using visual studio 2013 and i need to find out the execution time of my code(C++). Is there anyway that make me do that ?

Upvotes: 3

Views: 25709

Answers (3)

udit043
udit043

Reputation: 1620

This maybe one of the possible answer :

For Visual Studio : go to Tools / Options / Projects and Solutions / VC++ Project Settings and set Build Timing option to 'yes'. After that the time of every build will be displayed in the Output window.

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

For C++

For C++11

Upvotes: 2

Galik
Galik

Reputation: 48615

I use something like this:

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

Upvotes: 1

Konstantin Dedov
Konstantin Dedov

Reputation: 425

Try to use function clock() from <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;
}

Upvotes: 1

Related Questions