6
\$\begingroup\$

I am looking for a more efficient or shorter way to achieve the following output using the following code:

timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;

time_t rawtime;
struct tm * timeinfo;
char buffer [80];

time(&rawtime);
timeinfo = localtime(&rawtime);

strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", timeinfo);

char currentTime[84] = "";
sprintf(currentTime, "%s:%d", buffer, milli);
printf("current time: %s \n", currentTime);

Sample output:

current time: 2012-05-16 13:36:56:396

I would prefer not to use any third-party library like Boost.

\$\endgroup\$
  • \$\begingroup\$ You want to use %03d to format milli so you get leading zeros. And since your format is so close to ISO-8601, you might want to continue with it and use "." instead of ":" to separate the seconds and milliseconds. \$\endgroup\$ – xan May 24 '12 at 0:49
8
\$\begingroup\$

When you call gettimeofday it gives you the number of seconds since EPOCH too, so you don't need to call time again. And when you use output of localtime as input of strftime, you may omit the intermediate variable (not a very useful point though). So your code could be written like:

timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;

char buffer [80];
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&curTime.tv_sec));

char currentTime[84] = "";
sprintf(currentTime, "%s:%d", buffer, milli);
printf("current time: %s \n", currentTime);

an important note to be considered is that functions like localtime are not thread-safe, and you'd better use localtime_r instead.

\$\endgroup\$
  • \$\begingroup\$ It's worth to note that on Windows timeval::tv_sec is a long, while localtime expects a time_t. You might want explicitly convert it to the right type first. \$\endgroup\$ – Kentzo Feb 28 '18 at 7:46
  • \$\begingroup\$ sprintf(currentTime, "%s:%d", buffer, milli); will be wrong when milli<100. Use "%s:03d" to add zero-padding. \$\endgroup\$ – michaelmoo Jan 22 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.