Jmh2013
Jmh2013

Reputation: 2777

Running time of functions

I am wanting to print the running time of my functions. For some reason my timer always returns 0. Can anyone tell me why?

double RunningTime(clock_t time1, clock_t time2)
{
    double t=time1 - time2;
    double time = (t*1000)/CLOCKS_PER_SEC;
    return time;
}

int main()
{
     clock_t start_time = clock();


     // some code.....


    clock_t end_time = clock();

    std::cout << "Time elapsed: " << double(RunningTime(end_time, start_time)) << " ms";

    return 0;
}

I attempted to use gettimeofday and it still returned 0.

double get_time()
{
    struct timeval t;
    gettimeofday(&t, NULL);
    double d = t.tv_sec + (double) t.tv_usec/100000;
    return d;
}

int main()
{
        double time_start = get_time();

        //Some code......

        double time_end = get_time();

        std::cout << time_end - time_start;

    return 0;
}

Also tried using chrono and it gave me all kinds of build errors:

Upvotes: 3

Views: 5552

Answers (3)

user427390
user427390

Reputation:

A solution I have been using lately uses C++11's lambda functionality to time any arbitrary function call or series of actions.

#include <ctime>
#include <iostream>
#include <functional>

void timeit(std::function<void()> func) {
    std::clock_t start = std::clock();

    func();

    int ms = (std::clock() - start) / (double) (CLOCKS_PER_SEC / 1000);

    std::cout << "Finished in " << ms << "ms" << std::endl;
}

int main() {
    timeit([] {
        for (int i = 0; i < 10; ++i) {
            std::cout << "i = " << i << std::endl;
        } 
    });

    return 0;
}

Upvotes: 0

Jmh2013
Jmh2013

Reputation: 2777

After lots of trial and error I went with gettimeofday. Here is my code that I finally got to work properly.

double get_time()
{
    struct timeval t;
    gettimeofday(&t, NULL);
    double d = t.tv_sec + (double) t.tv_usec/1000000;
    return d;
}

int main()
{
    double time_start = get_time();

    //Some code.........

    double time_end = get_time();

    std::cout << time_end - time_start;

    return 0;
}

Upvotes: 0

Sergei Danielian
Sergei Danielian

Reputation: 5035

A timer tick is approximately equal to 1/CLOCKS_PER_SEC second, which is a millisecond resolution. To see a real (non-zero) number, you should either invoke a very long-time function or use another library with a higher time resolution facility:

  • new c++11x library chrono (use MSVS 2012)
  • boost::chrono (unfortunately, the library refers to a lot of others)
  • POSIX function gettimeofday, which gives you a 1 microsecond time resolution

Upvotes: 4

Related Questions