Nov 6, 2018

A C Elapsed Time Gotcha Involving localtime()

While trying to dither up a simple elapsed time routine I kept getting a result that had 19 hours added into it. The web examples that I worked from showed that after the difference of two times was taken it was converted to a tm struc using localtime(). I don't know if it's just my system (Ubuntu) but it kept producing a result with 19 hours in it in addition to the actual elapsed time (which was a couple of minutes). After wasting all morning I tried the following code which produced the result I was looking for.

time_t startime;
time_t endtime;
time_t elapsedtime;
struct tm * timeinfo;
char tBuffer[20] ;
startime = time(NULL) ;
  ----- some delay -----
endtime = time(NULL) ;
elapsedtime = difftime(endtime,startime) ;
timeinfo = gmtime(&elapsedtime) ;
strftime(tBuffer,19," [%H:%M:%S]",timeinfo) ;
printf("%s\\n",tBuffer) ;

Contact Us
This Site's Privacy Policy
Google's privacy policies