C++ Obtaining Milliseconds Time on Linux - Clock() Doesn't Seem to Work Properly

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

You could use gettimeofday at the start and end of your method and then difference the two return structs. You'll get a structure like the following:

struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
}

EDIT: As the two comments below suggest, clock_gettime(CLOCK_MONOTONIC) is a much better choice if you have it available, which should be almost everywhere these days.

EDIT: Someone else commented that you can also use modern C++ with std::chrono::high_resolution_clock, but that isn't guaranteed to be monotonic. Use steady_clock instead.

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

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';
}

///////////////////////////////////////////////////////////////////////////////

Get timestamp from X milliseconds ago in c++

#include <chrono>
#include <iostream>

int
main()
{
using namespace std::chrono;
auto old_time = time_point_cast<milliseconds>(system_clock::now()) - 100ms;
std::cout << old_time.time_since_epoch().count() << "ms\n";
}

This gets the current time UTC, truncates it to milliseconds precision, and then subtracts 100ms from that time point.

It then extracts the underlying value and prints it out (milliseconds since 1970-01-01 00:00:00.000 UTC).

What is a good way to find real time in milliseconds with C++?

#include <sys/time.h>

...

timeval tv;
gettimeofday (&tv, NULL);
return double (tv.tv_sec) + 0.000001 * tv.tv_usec;

c++ get milliseconds since some date

See std::clock()    

Time asked in microseconds but got in seconds

For the C++11 way, check the answer of bames53.


This gives the time in nanoseconds. In Ubuntu, C++, you need to add -lrt to the list of libraries you link to. Example (in a mainfile):

mm: main.cpp memory_manager.cc

g++ -Wextra -Wall -Wreorder -o mm main.cpp memory_manager.cc -lrt

#include <cstdint> // C++11. Use #include <stdint.h> instead
#include <ctime>

int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p)
{
return (((int64_t)timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -
(((int64_t)timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);
}

struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);

/* Code to be measured */

clock_gettime(CLOCK_MONOTONIC, &end);
int64_t time;
time = timespecDiff(&end, &start);
std::cout<<"Time: " << time << " ns\n";

Then convert to ms.

I go this from my example here.


Another interesting approach, that might be a bit off for what you want is this:

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
struct timeval start, end;

long mtime, seconds, useconds;

gettimeofday(&start, NULL);
usleep(2000);
gettimeofday(&end, NULL);

seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;

mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

printf("Elapsed time: %ld milliseconds\n", mtime);

return 0;
}

Source



Related Topics



Leave a reply



Submit