Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print current time (with milliseconds) using C++ / C++11

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

like image 231
Prospolon Avatar asked Apr 18 '13 07:04

Prospolon


People also ask

How to get current timestamp in Cpp?

Get the current time either using std::time() or std::chrono::system_clock::now() (or another clock type). std::put_time() (C++11) and strftime() (C) offer a lot of formatters to output those times.

How to get time in microseconds in c++?

A simple use case : auto start = std::chrono::high_resolution_clock::now(); ... auto elapsed = std::chrono::high_resolution_clock::now() - start; long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>( elapsed). count();

How to print the current date and time in C++ 11?

Following is a simple C implementation to get the current date and time: In C++ 11, we can also use std::chrono::system_clock::now (), which returns a time point representing the current point in time. That’s all about printing the current date and time in C.

Can I use C++11 to add milliseconds to time output?

to format time. I need to add milliseconds, so the output has the format: 16:56:12.321 The std c time functionality doesn't include milliseconds. If you have c++11 facilities available, you might look at std::chrono yes I can use c++11 ! I use VC11 I am aware of this, but I dont need uniform initialization here. This is irrelevant.

How can I get time in milliseconds in C?

The standard C library provides timespec_get. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer so you can get time in milliseconds.

Which library is used to print current date and time?

Here we have used chrono library to print current date and time . The chrono library is a flexible collection of types that tracks time with varying degrees of precision . The chrono library defines three main types as well as utility functions and common typedefs.


3 Answers

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

like image 130
Martin Goff Avatar answered Oct 13 '22 06:10

Martin Goff


You can use Boost's Posix Time.

You can use boost::posix_time::microsec_clock::local_time() to get current time from microseconds-resolution clock:

boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); 

Then you can compute time offset in current day (since your duration output is in the form <hours>:<minutes>:<seconds>.<milliseconds>, I'm assuming they are calculated as current day offset; if they are not, feel free to use another starting point for duration/time interval):

boost::posix_time::time_duration td = now.time_of_day(); 

Then you can use .hours(), .minutes(), .seconds() accessors to get the corresponding values.
Unfortunately, there doesn't seem to be a .milliseconds() accessor, but there is a .total_milliseconds() one; so you can do a little subtraction math to get the remaining milliseconds to be formatted in the string.

Then you can use sprintf() (or sprintf()_s if you are interested in non-portable VC++-only code) to format those fields into a raw char buffer, and safely wrap this raw C string buffer into a robust convenient std::string instance.

See the commented code below for further details.

Output in console is something like:

11:43:52.276


Sample code:

///////////////////////////////////////////////////////////////////////////////  #include <stdio.h>      // for sprintf()  #include <iostream>     // for console output #include <string>       // for std::string  #include <boost/date_time/posix_time/posix_time.hpp>   //----------------------------------------------------------------------------- // Format current time (calculated as an offset in current day) in this form: // //     "hh:mm:ss.SSS" (where "SSS" are milliseconds) //----------------------------------------------------------------------------- std::string now_str() {     // Get current time from the clock, using microseconds resolution     const boost::posix_time::ptime now =          boost::posix_time::microsec_clock::local_time();      // Get the time offset in current day     const boost::posix_time::time_duration td = now.time_of_day();      //     // Extract hours, minutes, seconds and milliseconds.     //     // Since there is no direct accessor ".milliseconds()",     // milliseconds are computed _by difference_ between total milliseconds     // (for which there is an accessor), and the hours/minutes/seconds     // values previously fetched.     //     const long hours        = td.hours();     const long minutes      = td.minutes();     const long seconds      = td.seconds();     const long milliseconds = td.total_milliseconds() -                               ((hours * 3600 + minutes * 60 + seconds) * 1000);      //     // Format like this:     //     //      hh:mm:ss.SSS     //     // e.g. 02:15:40:321     //     //      ^          ^     //      |          |     //      123456789*12     //      ---------10-     --> 12 chars + \0 --> 13 chars should suffice     //       //      char buf[40];     sprintf(buf, "%02ld:%02ld:%02ld.%03ld",          hours, minutes, seconds, milliseconds);      return buf; }  int main() {     std::cout << now_str() << '\n';     }  /////////////////////////////////////////////////////////////////////////////// 
like image 24
Mr.C64 Avatar answered Oct 13 '22 06:10

Mr.C64


Here is a solution I found without using boost

std::string getCurrentTimestamp()
{
using std::chrono::system_clock;
auto currentTime = std::chrono::system_clock::now();
char buffer[80];

auto transformed = currentTime.time_since_epoch().count() / 1000000;

auto millis = transformed % 1000;

std::time_t tt;
tt = system_clock::to_time_t ( currentTime );
auto timeinfo = localtime (&tt);
strftime (buffer,80,"%F %H:%M:%S",timeinfo);
sprintf(buffer, "%s:%03d",buffer,(int)millis);

return std::string(buffer);
}
like image 36
Enrico Pintus Avatar answered Oct 13 '22 07:10

Enrico Pintus