188

In Java, we can use System.currentTimeMillis() to get the current timestamp in Milliseconds since epoch time which is -

the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

In C++ how to get the same thing?

Currently I am using this to get the current timestamp -

struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds

cout << ms << endl;

This looks right or not?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
AKIWEB
  • 19,008
  • 67
  • 180
  • 294

5 Answers5

344

If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:

#include <chrono>

// ...

using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
);
Oz.
  • 5,299
  • 2
  • 23
  • 30
  • 146
    Nice. Add count() at the end of the line to get number of milliseconds in a fundamental type format. – P1r4nh4 Nov 24 '14 at 14:36
  • Will this be same if we use `steady_clock` instead of `system_clock`? Will both the epoch be same? – arsenal Jul 26 '15 at 22:09
  • 1
    @lining: Both epochs are likely to be the same, but their values could be different. `steady_clock` will always progress forward, it is a true measure of the time since its epoch while `system_clock` may be a representation of the logical time since the epoch. For every leap second the two could grow further apart depending on the system's implementation. – Oz. Jul 27 '15 at 20:30
  • Ok, do you know what is the epoch for `steady_clock` as compared to `system_clock`? To me epoch for the `system_clock` (on g++/linux) is in fact the system epoch, but for steady_clock it's something else I guess . And also let's say if we use `system_clock`, is there any disadvantage in leap year? – arsenal Jul 27 '15 at 20:43
  • 4
    As far as I know, the epoch for each of the clocks is implementation dependent. Convention is for `system_clock`'s to be the same as the UNIX epoch, but the spec only says it must be the system-wide real time wall clock. There is no requirement for the `steady_clock` to match reality, only that it only move forward. – Oz. Jul 27 '15 at 23:22
  • What's the advantage of using the c++11 chrono library as opposed to the gettimeofday? – schrödinbug Nov 10 '16 at 18:36
  • 1
    @Jason Besides gettimeofday not being available on Windows, the chrono library can give you higher resolution (gtod is limited to microseconds), provides time units in a type-safe way so the compiler can enforce unit conversions, and works with normal arithmetic operators (adding `timeval` structs is annoying). – Oz. Nov 10 '16 at 19:02
  • @P1r4nh4 I needed it in `int` but when I use `.count` it gives me a negative number. – Noitidart Jan 27 '17 at 06:19
  • How do I convert this to int64_t? – Pototo Feb 28 '17 at 19:41
  • @Pototo as P1r4nh4 stated, call `.count()`. Check out the linked documentation for more information. http://en.cppreference.com/w/cpp/chrono/duration – Oz. Mar 22 '17 at 02:00
  • 9
    Javascript developers are laughing at me seeing this :( – Fantastory Jan 29 '18 at 12:52
  • 1
    @Noitidart ,`long int ns = std::chrono::system_clock::now().time_since_epoch().count();` appears to return the result in nanoseconds. To get it as an int, I'm doing `int ms = ns / 1000000 - 1550000;`, which messes with the offsets, but I'm just measuring time deltas in my project. – ESPeach Feb 28 '19 at 09:38
  • How can I convert this epoch ms to a datetime format where I can extract the date and time like 07/27/2020 and 20:37:46.239522 respectively? – Potion Aug 14 '20 at 20:20
  • @Potion See https://stackoverflow.com/a/58610754/321937 – Oz. Aug 19 '20 at 18:19
51

Since C++11 you can use std::chrono:

  • get current system time: std::chrono::system_clock::now()
  • get time since epoch: .time_since_epoch()
  • translate the underlying unit to milliseconds: duration_cast<milliseconds>(d)
  • translate std::chrono::milliseconds to integer (uint64_t to avoid overflow)
#include <chrono>
#include <cstdint>
#include <iostream>

uint64_t timeSinceEpochMillisec() {
  using namespace std::chrono;
  return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}

int main() {
  std::cout << timeSinceEpochMillisec() << std::endl;
  return 0;
}
Alessandro Pezzato
  • 8,603
  • 5
  • 45
  • 63
49

use <sys/time.h>

struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;

refer this.

Community
  • 1
  • 1
Trying
  • 14,004
  • 9
  • 70
  • 110
  • good solution, also I think it should be gettimeofday(&tp,NULL); – Adem Dec 25 '14 at 11:01
  • 6
    First of all, this is C, not C++. Secondly, there are problems with gettimeofday, see [this](https://blog.habets.se/2010/09/gettimeofday-should-never-be-used-to-measure-time) for example. – rustyx Feb 15 '16 at 15:41
32

This answer is pretty similar to Oz.'s, using <chrono> for C++ -- I didn't grab it from Oz. though...

I picked up the original snippet at the bottom of this page, and slightly modified it to be a complete console app. I love using this lil' ol' thing. It's fantastic if you do a lot of scripting and need a reliable tool in Windows to get the epoch in actual milliseconds without resorting to using VB, or some less modern, less reader-friendly code.

#include <chrono>
#include <iostream>

int main() {
    unsigned __int64 now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
    std::cout << now << std::endl;
    return 0;
}
kayleeFrye_onDeck
  • 6,648
  • 5
  • 69
  • 80
  • I get a negative number `-560549313` this is not right, right? – Noitidart Jan 27 '17 at 06:22
  • 1
    @Noitidart Can you tell me what platform and C++ compiler you're using? I use this thing all the time with automation tools, and have never seen a negative output o.0 More than happy to check it though. Also, is that a direct copy, or modified/integrated program? Just want to make sure it's originating from this code only. – kayleeFrye_onDeck Jan 27 '17 at 18:41
  • 5
    Ah @kayleeFrye_onDeck its because I was using `int`! `int nowms = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count();`. I swithced that to `int64_t` and it works! Thanks so much for asking for more info to help! – Noitidart Jan 27 '17 at 23:43
  • 2
    `unsigned long long` is more portable, and `__int64` is only available on MSVC. – S.S. Anne Apr 01 '20 at 13:35
  • 2
    there is no `__int64` type in standard C++. One can use `std::int64_t` instead. – Mariusz Jaskółka Jul 29 '20 at 07:09
14

If using gettimeofday you have to cast to long long otherwise you will get overflows and thus not the real number of milliseconds since the epoch: long int msint = tp.tv_sec * 1000 + tp.tv_usec / 1000; will give you a number like 767990892 which is round 8 days after the epoch ;-).

int main(int argc, char* argv[])
{
    struct timeval tp;
    gettimeofday(&tp, NULL);
    long long mslong = (long long) tp.tv_sec * 1000L + tp.tv_usec / 1000; //get current timestamp in milliseconds
    std::cout << mslong << std::endl;
}
rli
  • 1,745
  • 1
  • 14
  • 25