C++11 Time – How to Print Current Time with Milliseconds Using C++

c++c++11linuxtimewindows

Currently I use this code

string now() {
    time_t t = time(0);
    char buffer[9] = {0};

    strftime(buffer, 9, "%H:%M:%S", localtime(&t));
    return string(buffer);
}

to format time. I need to add milliseconds, so the output has the format: 16:56:12.321

Best Answer

Don't waste your time with Boost (I know many will be offended by this statement and consider it heresy).

This discussion contains two very workable solutions that don't require you to enslave yourself to non-standard, 3rd party libraries.

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

http://linux.die.net/man/3/clock_gettime

References to gettimeofday can be found here at opengroup.org

Related Question