views:

164

answers:

3

I'm a windows user, and I'm learning C. I use Codeblocks and visual c++ 2008 express at home to write simple C command line programs (I'm a beginner) and I find really useful when codeblocks adds a few lines at the end with the time it takes (example: "Process returned 0 (0x0) execution time : 6.848 s").

I want to add this functionality to the .exe so I can 'benchmark' or 'test' the program on a few computers. I tried using time(NULL) but it only works with 1 second precision.

I also found very interesting answers here (I'm actually looking for the same thing): http://stackoverflow.com/questions/2173323/calculating-time-by-the-c-code

The solution proposed by Mark Wilkins, works fine on visual c++ 2008 express on my windows 64 bit PC, but the .exe does not work anywhere else. Am I doing something wrong?

I would like a method to count elapsed wall time for my programs, that must have 32bit compatibility. Thanks in advance!

+2  A: 

There's a function in time.h header clock_t clock();

It returns a number of hardware timer clocks expired since launch of the program To get real time you can divide that number by constant CLOCKS_PER_SEC which is also defined in time.h

The full method would be:

void print_time_since_launch() {
    printf ("Execution time %f", clock() / CLOCKS_PER_SEC);
}

You can use it in your program like this:

static clock_t s_start_time;
void start_clock() { s_start_time = clock(); }
void display_execution_time() { 
    clock_t now = clock();
    double secs = (now - s_start_time) / (double)CLOCKS_PER_SEC;
    printf("Execution time: %g secs\n", secs);
}
int main() {
    start_clock();
    /* do your thing */
    display_execution_time();
}
buratinas
A: 

The reason that it does not work on some PCs is ... See my answer on

http://stackoverflow.com/questions/2607263/how-precise-is-the-internal-clock-of-a-modern-pc/2615977#2615977

Romain Hippeau
A: 
#include <mmsystem.h>

int
main() {
    DWORD start = timeGetTime();
    //Do work
    DWORD end = timeGetTime(); 
    printf("execution time: %.3f s\n", float(end - start) / 1000.0f);
}
Andreas Brinck