Running time of functions

c++, clock, time

Solution

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

Problem

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: - error: #error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options. - warning: 'auto' will change meaning in C++0x; please remove it - error: ISO C++ forbids declaration of 't1' with no type error: 'std::chrono' has not been declared error: request for member 'count' in '(t2 - t1)', which is of non-class type 'int' int main() { auto t1 = std::chrono::high_resolution_clock::now(); ``` //Some code...... auto t2 = std::chrono::high_resolution_clock::now(); std::cout << "Time elapsed: " << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count() << " milliseconds\n"; return 0; } ```

Original source

Related problems