Reputation: 19612
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?
Upvotes: 197
Views: 498280
Reputation: 1885
If using gettimeofday you have to cast to long long
otherwise you will get overflows and thus not the 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 about 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;
}
Upvotes: 14
Reputation: 8802
Since C++11 you can use std::chrono
:
std::chrono::system_clock::now()
.time_since_epoch()
duration_cast<milliseconds>(d)
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;
}
Upvotes: 58
Reputation: 6958
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;
}
Upvotes: 32
Reputation: 14278
use <sys/time.h>
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
refer this.
Upvotes: 49
Reputation: 5458
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()
);
Upvotes: 357