NO

Author Topic: How to measure the running time of a program ?  (Read 6245 times)

andre104

  • Guest
How to measure the running time of a program ?
« on: October 29, 2008, 03:00:11 AM »
In UNIX/UNIX-like OSes, you can use the time command.

I'm trying to implement that in Windows, and my first quick attempt this :
Code: [Select]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[]){
clock_t start,end;
int x;
char command[100];

if (argc > 1){

for (int x = 1; x < argc; x++){
strcat(command,argv[x]);
strcat(command," ");
}

start = clock();
system(command);
printf("%f\n",(end-start)/CLOCKS_PER_SEC);
end = clock();
}
return 0;

}

The last output is always "0.0000", which means the execution time is not captured properly.
How can I fix that ? Maybe some Win32 API needed ?

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2115
Re: How to measure the running time of a program ?
« Reply #1 on: October 29, 2008, 06:54:01 AM »

Code: [Select]
...
start = clock();
system(command);
end = clock();
printf("%f\n",(float)(end-start)/CLOCKS_PER_SEC);
...
May the source be with you

severach

  • Guest
Re: How to measure the running time of a program ?
« Reply #2 on: October 30, 2008, 02:43:42 AM »
GetTickCount() works great for me.

andre104

  • Guest
Re: How to measure the running time of a program ?
« Reply #3 on: October 30, 2008, 08:35:28 AM »
Ah, silly mistake  :P

I made some workarounds, and the code works :

timeit.c
Code: [Select]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[]){
clock_t start,end;
int x;
char command[100];

if (argc > 1){
strcpy(command," ");

for (x = 1; x < argc; x++){
strcat(command,argv[x]);
strcat(command," ");
}

start = clock();
system(command);
end = clock();
printf("%f\n",(float)(end-start)/CLOCKS_PER_SEC);
}
return 0;
}

Now if I invoke the program, e.g :
timeit python matrixmultiplication.py 10, it will print the number estimated to be the running time

But i think system() has overhead
Any better solution ?

Offline AlexN

  • Global Moderator
  • Member
  • *****
  • Posts: 394
    • Alex's Link Sammlung
Re: How to measure the running time of a program ?
« Reply #4 on: October 30, 2008, 09:41:09 AM »
But i think system() has overhead
Any better solution ?

I have an old program, that i found many years ago and which i ported to Pelles C. It starts other programs without system. Perhaps it is a better solution, perhaps not - look at it. ;-)
best regards
 Alex ;)

pgoh

  • Guest
Re: How to measure the running time of a program ?
« Reply #5 on: November 11, 2008, 08:26:26 AM »
But i think system() has overhead
Any better solution ?

The overhead to system() is so small that you shouldn't really care about it. Unless you're timing operations that are so trivial they execute faster than a call to system.