Search code examples
cctime

Get interval between 2 operations using ctime?


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


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.