Dominique
Dominique

Reputation: 17493

Why is my second time_t variable not shown correctly

I would like to measure how long a particular operation takes, therefore I've written the following piece of code:

for (int counter2 = 0; counter2 <= 10; counter2++) { // I'll do the test 10 times,
                                                     // for having reliable results

    time_t ltime;
    time(&ltime); // What's the time at the beginning?

    for (counter = 0; counter <= 1000000; counter++) {
        Do_Something();
    }

    time_t ltime2;
    time(&ltime2); // What's the time after having launched Do_Something()?
    printf("Times:First=[%d], Second=[%d]\n", ltime, ltime2);

}

I'm expecting something like:

Times: First=[1559574983], Second=[1559574985]
Times: First=[1559574990], Second=[1559574999]

Instead I get this:

Times: First=[1559574983], Second=[0]
Times: First=[1559574990], Second=[0]

I've already debugged, and ltime2 seems to be correct. What am I doing wrong?

Upvotes: 0

Views: 117

Answers (2)

Dominique
Dominique

Reputation: 17493

Thanks for the quick replies.
Just for the record, hereby the final solution I'm using (combining the mentioned other Stackoverflow post and difftime() function):

printf("First=[%ju], Second=[%ju], Difference=[%f]\n", (uintmax_t) ltime, 
                                                       (uintmax_t) ltime2, 
                                                       difftime(ltime2, ltime));

Upvotes: 0

bruno
bruno

Reputation: 32586

The format "%d" is not the right one in your case, but you don't have to take care of the type supporting time_t just replace

 printf("Times:First=[%d], Second=[%d]\n", ltime, ltime2);

by

std::cout << "Times:First=[" << ltime << "], Second=[" << ltime2 << "]" << std::endl;

If for an obscure reason you really want to use a C printf as proposed by @Lightness Races in Orbit 3 in a remark you can convert the value to an other type (hopping enough long) and use the format compatible to that type, see Format specifier to print time(0) in C

Upvotes: 4

Related Questions