Bartc said:
That's a good point. clock() should give the execution time of the
program doing the timing.
Nevertheless, it seemed to work! Or at least gave sensible results.
Maybe something to with Windows, and the OP wanted this on Windows.
Here is a more robust version of 'time'. Still not as good as the UNIX
version of course. This code is NOT standard C; it depends on
*gettimeofday* , which is specific to POSIX systems.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
int timediff(struct timeval *diff, struct timeval *end, struct timeval
*begin);
int main(int argc, char **argv)
{
struct timeval start, end, diff;
int ctr;
size_t cmdlen = 0;
char *cmd;
char *usage = "Program COMMAND [COMMAND ARGS] [...]\n";
if (!system(NULL)) {
puts("No command interpreter!");
return EXIT_FAILURE;
}
if (argc > 1) {
for (ctr = 1; ctr < argc; ctr++) cmdlen += strlen(argv[ctr]);
cmdlen += 1;
if ((cmd = calloc(cmdlen, sizeof *cmd)) == NULL) {
puts("Memory allocation failed.");
return EXIT_FAILURE;
}
else for (ctr = 1; ctr < argc; ctr++) strcat(cmd, argv[ctr]);
}
else fputs(usage, stderr);
gettimeofday(&start, NULL);
if (system(cmd) == -1) {
puts("system() failed.");
free(cmd);
return EXIT_FAILURE;
}
gettimeofday(&end, NULL);
timediff(&diff, &end, &start);
printf("Start:\t%lds %ldmsec\nEnd:\t%lds %ldmsec\nDiff.
\t%lds %ldmsec\n",
start.tv_sec, start.tv_usec, end.tv_sec, end.tv_usec,
diff.tv_sec,
diff.tv_usec);
return 0;
}
int timediff(struct timeval *result, struct timeval *x, struct timeval
*y)
/* Code below is copied from glibc documentation */
{
/* Perform the carry for the later subtraction by updating Y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
`tv_usec' is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}