Searched for answer for this but couldn’t find anything. The closest I could find was
difftime returning 0 when there is clearly a difference Which has a great explanation that has to do with how the arguments are pushed onto the stack and what the format expects, but I think my issue is different:
I’ve made as simple of an example as possible. Suppose I have the following code in C:
time_t starttime = time(NULL)
somefunction();
time_t newtime = time(NULL)
fprintf(stderr, "starttime %f and difftime %f\n", starttime, difftime(newtime, starttime));
fprintf(stderr, "difftime %f and starttime %f\n", difftime(newtime, starttime), starttime);
return 0;
And somefunction is some function that runs for 1 or 2 seconds. The output I get for this is:
starttime 2.000000 and difftime 0.000000
difftime 2.000000 and starttime 0.000000
I don’t even know where to begin my question. Why is it when I swap the order, the outputted values are still the same? Furthermore, why is one of the values 0? This is the same whether I use %f, %d, %lu, %llu, etc. Is there a stack-argument explanation to this? What is fprintf really doing internally?
Thank you. I’ve wasted too much of my life trying to debug this and I really would appreciate your help!
starttimeis atime_t, but you’re to print it with a%f, which expects adouble. Evidently, on your platform,time_tis some integer type instead.Likely, your platform’s calling convention for variable-argument-list functions like
fprintf()passes floating point arguments in a different location from integer arguments.The
difftime()function is likely returning 2.0, which is being passed in the first floating-point argument location, which is why the first%fprints a 2.0 in both cases. The second floating-point argument location appears to contain a zero, so the second%fprints a zero in both cases. Thetime_targument is being placed in a different location that isn’t being examined by thefprintf()code at all.