Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the time in milliseconds in C++

Tags:

c++

time

In Java you can do this:

long now = (new Date()).getTime();

How can I do the same but in C++?

like image 223
atomsfat Avatar asked May 14 '10 04:05

atomsfat


People also ask

How do you measure time in milliseconds?

To convert an hour measurement to a millisecond measurement, multiply the time by the conversion ratio. The time in milliseconds is equal to the hours multiplied by 3,600,000.

How to get time in c?

The time() function is defined in time. h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.

How long is a millisecond?

A millisecond (ms or msec) is one thousandth of a second and is commonly used in measuring the time to read to or write from a hard disk or a CD-ROM player or to measure packet travel time on the Internet. For comparison, a microsecond (us or Greek letter mu plus s) is one millionth (10-6) of a second.


1 Answers

Because C++0x is awesome

namespace sc = std::chrono;

auto time = sc::system_clock::now(); // get the current time

auto since_epoch = time.time_since_epoch(); // get the duration since epoch

// I don't know what system_clock returns
// I think it's uint64_t nanoseconds since epoch
// Either way this duration_cast will do the right thing
auto millis = sc::duration_cast<sc::milliseconds>(since_epoch);

long now = millis.count(); // just like java (new Date()).getTime();

This works with gcc 4.4+. Compile it with --std=c++0x. I don't know if VS2010 implements std::chrono yet.

like image 113
deft_code Avatar answered Sep 18 '22 01:09

deft_code