Question

I am interested in showing the execution time for a program in C, at diverse points, using ctime. I have tried something like that, but it must not be right...

int main() {

    time_t tm1, tm2;
    tm1 = time(NULL);
    sleep(2);
    tm2 = ctime(tm1);

    printf("%d\n", tm2-tm1);
    return 0;
}

Do you have any suggestion or a proper example? Thanks in advance

Was it helpful?

Solution

ctime() returns a string representation of the time passed into it.

If you want a simple elapsed time, just:

    time_t t1, t2;
    t1 = time(0);
    sleep(2);
    t2 = time(0);

    printf("Elapsed: %d\n", t2 - t1);

See man ctime and man 2 time.

OTHER TIPS

You can use the time function to get the current time and the difftime function to compute the difference, in seconds, between two times (error handling omitted):

time_t t0, t1;
t0 = time(NULL);
foo();
t1 = time(NULL);
printf("foo() took %f seconds.\n", difftime(t1, t0));

However, time_t is intended for measuring calendar times. The time function typically has a one-second interval. If this is too coarse, you can try using clock_t and the clock function (error handling omitted again):

clock_t t0, t1;
t0 = clock();
foo();
t1 = clock();
printf("foo() took %f seconds.\n", (double)((t1 - t0) / CLOCKS_PER_SEC));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top