1

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): 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
  • Someone, add the tag 'c' Commented Apr 17, 2010 at 19:33
  • If you ever plan to switch to GNU Linux, you will be able to use the 'time' command. Commented Apr 17, 2010 at 20:28

3 Answers 3

2

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(); } 
Sign up to request clarification or add additional context in comments.

Comments

0

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

How precise is the internal clock of a modern PC?

Comments

0
#include <mmsystem.h> int main() { DWORD start = timeGetTime(); //Do work DWORD end = timeGetTime(); printf("execution time: %.3f s\n", float(end - start) / 1000.0f); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.