I tried to find the answer all over the internet. I need a timestamp in seconds with microsecond resolution.
boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
// not really getting any further here
double now_seconds = 0; // a value like 12345.123511, time since epoch in seconds with usec precision
UPDATE:
It is sufficient to use the beginning of the current day as the epoch -- i.e. a 24h timestamp.
N.B. This answer provides a generic method that allows an arbitrary epoch, since it was written before the update. fonZ's answer is a good simplification when a timestamp relative to beginning of a current day is needed.
I'm not aware of an existing function in the library that would do exactly what you ask for, but with the help of documentation it is simple to come up your own in a few lines.
Subtract your ptime from a ptime representing the epoch, to get a time_duration representing the amount of time elapsed since epoch. The time_duration class provides total_microseconds(). Scale the result appropriately to get seconds.
Code Sample
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/format.hpp>
#include <iostream>
double seconds_from_epoch(boost::posix_time::ptime const& t)
{
boost::posix_time::ptime const EPOCH(boost::gregorian::date(1970,1,1));
boost::posix_time::time_duration delta(t - EPOCH);
return (delta.total_microseconds() / 1000000.0);
}
int main()
{
boost::posix_time::ptime now(boost::posix_time::microsec_clock::local_time());
std::cout << boost::format("%0.6f\n") % seconds_from_epoch(now);
return 0;
}
Sample on Coliru
Console output:
1497218065.918929
I solved my problem, at least it seems to work correctly (didn't bother to check the actual values so be my guest if you want to correct me).
boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
double sec = now.time_of_day().total_microseconds()/1000000.0;
Related
I need to measured elapsed time in ms
I need to store the start time as a primitive type
I need to retrieve the start time as a primitive type, when making the comparison to determine how much time has elapsed
Any suggestions?
I have C++17 and do not want to use any external libraries (like boost).
std::chrono would be fine if someone could explain to me how to convert the elapsed time to/from a primitive. I'm not very good at C++.
resolution accuracy is not important.. if it is off by tens of ms that's ok, I just need to implement a delay.. e.g. 100ms or 1.5s
Because you are storing the start time, you should use std::chrono::system_clock. Its epoch is stable, and will not change with time. Other std::chrono clocks have an epoch that may change between runs of a program, and thus time points stored by one run and read back in by a subsequent run may not be consistent.
To get the current time in milliseconds:
auto now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
I like to use either a using directive or a namespace alias to make such code less verbose:
using namespace std::chrono;
auto now = time_point_cast<milliseconds>(system_clock::now());
To convert now into a signed 64 bit integral type:
auto now_i = now.time_since_epoch().count();
To convert now_i back into a time_point:
time_point<system_clock, milliseconds> prev{milliseconds{now_i}};
To compare time_points:
if (now > prev)
...
Everything above is in the header <chrono>:
#include <chrono>
You can simply do this by:
double time = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC;
See the below code for better understanding.
#include <iostream>
#include <time.h>
using namespace std;
int main() {
double start = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC;
for(int i=0;i<1e9;i++);
double end = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC;
double time_taken = end - start;
cout << time_taken << "ms\n";
return 0;
}
Include the header file:
#include <time.h> // include this
I am converting CLI C++ code to standard C++, and i have a piece of code that gets a UINT64 number (from a remote server - so i can't change to format/precision of the time i get) and converts it into DateTime object and later outputs the following value: myDatetime.ToString("dd/MM/yyyy hh:mm:ss.fffffff tt").
I haven't found a way to convert unsigned int 64 into time in C++.
The following code does nothing for numbers so big (that's the 64bit number i get from the server).
time_t rawtime=131274907755873979
localtime_s(&timeinfo, &rawtime);
I need some help :)
My question wan't answered in the thread Convert Epoch Time string to Time since it doesn't work for numbers as large as i need. For example the number 131274907755873979 which is what i get from the server. The function ctime for that value simply returns NULL.
I need a way to convert between the time i get as a unsigned int64 into standard C++ time object.
std::string LongToString(int64_t longDate) {
char buff[128];
std::chrono::duration<int64_t, std::milli> dur(longDate);
auto tp = std::chrono::system_clock::time_point(
std::chrono::duration_cast<std::chrono::system_clock::duration>(dur));
std::time_t in_time_t = std::chrono::system_clock::to_time_t(tp);
strftime(buff, 128, "%Y-%m-%d %H:%M:%S", localtime(&in_time_t));
std::string resDate(buff);
return resDate;
}
This is a case with bsoncxx::types::b_date get_date().to_int64() MongoDB.
The DateTime saved with int64_t.
You have not told us how the existing code converts that number into a DateTime. Let us suppose that it does so by invoking this constructor: DateTime( long long ticks ).
According to the documentation of that constructor of DateTime,
long long ticks A date and time expressed in the number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar.
On the other hand, according to the documentation of localtime_s and the documentation of time_t, localtime_s() requires
the number of seconds (not counting leap seconds) since 00:00, Jan 1 1970 UTC.
So, you first need to convert 100-nanosecond intervals to seconds, and then convert from January 1, 0001 to January 1, 1970.
Using Howard Hinnant's datetime library this computation can be done quite easily. It works with VS 2013 and later.
#include "tz.h"
#include <cstdint>
#include <string>
#include <iostream>
std::string
FILETIME_to_string(std::uint64_t i)
{
using namespace std;
using namespace std::chrono;
using namespace date;
using FileTime = duration<int64_t, ratio<1, 10000000>>;
auto const offset = sys_days{jan/1/1970} - sys_days{jan/1/1601};
auto tp = sys_days{jan/1/1970} + (FileTime{static_cast<int64_t>(i)} - offset);
return format("%d/%m/%Y %I:%M:%S %p", make_zoned("Etc/GMT-2", tp));
}
int
main()
{
std::cout << FILETIME_to_string(131274907755873979) << '\n';
}
This skips DateTime and goes straight to the string. I wasn't sure what you are wanting with tt in the format. But whatever it is, it can be handled.
This library builds on the C++11 <chrono> library. So the first thing to do is to create a duration to represent the windows tick size (100 ns). Then just compute the offset between the two epochs and subtract it from the input, and form a std::chrono::time_point. Now you can format that time_point however you want.
The program above outputs:
29/12/2016 03:12:55.5873979 PM
If you use VS 2017 you'll be able to make offset constexpr, making the conversion more efficient.
I have to instantiate an object of a custom library class that takes nanoseconds since 'epoch' in UTC time to construct:
class utc_time
{
public:
utc_time(TYPE nanoseconds_since_epoch):
_nanoseconds_since_epoch(nanoseconds_since_epoch){}
private:
TYPE _nanoseconds_since_epoch;
};
what I have as my input is nanoseconds since 'midnight' in UTC time. Naturally, I need to get the epoch till last midnight nanoseconds(in UTC) to add it to my input and supply it to my class constructor.
I know we have gtime that may be helpful, but I dont know how to extract the required information.
I appreciate your clues
In C++11 and later, <chrono> can be used to do this very easily:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
using namespace std;
using days = duration<int, ratio<86400>>;
nanoseconds last_midnight =
time_point_cast<days>(system_clock::now()).time_since_epoch();
cout << last_midnight.count() << '\n';
}
In deed, nanoseconds since Epoch = nanoseconds since midnight + 1e9 * calendar time of last midnight. You lack the latter value. You can built it with a conjunction of ::gmtime() and ::mktime().
#include <ctime>
std::time_t last_midnight()
{
// compute "now"
std::tm& tm = *::gmtime(NULL);
// move it to "last midnight"
tm.tm_hour = 0;
tm.tm_min = 0;
tm.tm_sec = 0;
// get time_t back
return ::mktime(&tm);
}
You may find interest in using ::gmtime_r() (re-entrant version) instead of ::gmtime().
What would be the next best thing for strptime when we have the datetime string with millisseconds?
Given:
"30/03/09 16:31:32.121"
we can't use the regular strptime because struct tm doesn't store millisseconds. Is there a new class that can achieve this?
I would parse these fields manually (reading into int and double for the seconds), then use days_from_civil to convert the year/month/day into a chrono::system_clock::time_point:
std::chrono::system_clock::time_point t(days(days_from_civil(y, m, d)));
where days is:
using days = std::chrono::duration<int, std::ratio<86400>>;
Then you can add to that the hours, minutes and seconds. To handle the fractional seconds you'll need to do a slight dance:
double s;
your_stream >> s; // 32.121
using namespace std::chrono;
duration<double> dsecs(s);
seconds sec = duration_cast<seconds>(dsecs);
milliseconds ms = duration_cast<milliseconds>(dsecs - sec);
t += sec + ms;
If you prefer, use round from here for your milliseconds conversion:
milliseconds ms = round<milliseconds>(dsecs - sec);
duration_cast is truncate towards zero. There are other rounding modes: floor, round, ceil, at this link.
Wrap it all up in a neat function for easy reuse. :-)
The above code all assumes UTC. If your date/time that you are parsing is known to be offset from UTC, you can add/subtract that offset. All known implementations of system_clock track Unix time, which is seconds since 1970-01-01 in the UTC time zone.
Update
Since writing this answer I've developed a more general library that the OP seemed to be seeking at that time. It can parse a wide variety of sub second precisions directly into a std::chrono::system_clock::time_point like this:
#include "date/date.h"
#include <iostream>
#include <sstream>
int
main()
{
std::istringstream in{"30/03/09 16:31:32.121\n"
"30/03/09 16:31:32.1214"};
std::chrono::system_clock::time_point tp;
in >> date::parse("%d/%m/%y %T", tp);
using namespace date;
std::cout << tp << '\n';
in >> date::parse(" %d/%m/%y %T", tp);
std::cout << tp << '\n';
}
This outputs:
2009-03-30 16:31:32.121000
2009-03-30 16:31:32.121400
This library uses the same techniques and tools as I originally described, but is packaged up and ready to go as a single header library.
Does anyone know how to calculate time difference in C++ in milliseconds?
I used difftime but it doesn't have enough precision for what I'm trying to measure.
I know this is an old question, but there's an updated answer for C++0x. There is a new header called <chrono> which contains modern time utilities. Example use:
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds milliseconds;
Clock::time_point t0 = Clock::now();
std::this_thread::sleep_for(milliseconds(50));
Clock::time_point t1 = Clock::now();
milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
std::cout << ms.count() << "ms\n";
}
50ms
More information can be found here:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm
There is also now a boost implementation of <chrono>.
You have to use one of the more specific time structures, either timeval (microsecond-resolution) or timespec (nanosecond-resolution), but you can do it manually fairly easily:
#include <time.h>
int diff_ms(timeval t1, timeval t2)
{
return (((t1.tv_sec - t2.tv_sec) * 1000000) +
(t1.tv_usec - t2.tv_usec))/1000;
}
This obviously has some problems with integer overflow if the difference in times is really large (or if you have 16-bit ints), but that's probably not a common case.
if you are using win32 FILETIME is the most accurate that you can get:
Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
So if you want to calculate the difference between two times in milliseconds you do the following:
UINT64 getTime()
{
SYSTEMTIME st;
GetSystemTime(&st);
FILETIME ft;
SystemTimeToFileTime(&st, &ft); // converts to file time format
ULARGE_INTEGER ui;
ui.LowPart=ft.dwLowDateTime;
ui.HighPart=ft.dwHighDateTime;
return ui.QuadPart;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
//! Start counting time
UINT64 start, finish;
start=getTime();
//do something...
//! Stop counting elapsed time
finish = getTime();
//now you can calculate the difference any way that you want
//in seconds:
_tprintf(_T("Time elapsed executing this code: %.03f seconds."), (((float)(finish-start))/((float)10000))/1000 );
//or in miliseconds
_tprintf(_T("Time elapsed executing this code: %I64d seconds."), (finish-start)/10000 );
}
The clock function gives you a millisecond timer, but it's not the greatest. Its real resolution is going to depend on your system. You can try
#include <time.h>
int clo = clock();
//do stuff
cout << (clock() - clo) << endl;
and see how your results are.
You can use gettimeofday to get the number of microseconds since epoch. The seconds segment of the value returned by gettimeofday() is the same as that returned by time() and can be cast to a time_t and used in difftime. A millisecond is 1000 microseconds.
After you use difftime, calculate the difference in the microseconds field yourself.
You can get micro and nanosecond precision out of Boost.Date_Time.
If you're looking to do benchmarking, you might want to see some of the other threads here on SO which discuss the topic.
Also, be sure you understand the difference between accuracy and precision.
I think you will have to use something platform-specific. Hopefully that won't matter?
eg. On Windows, look at QueryPerformanceCounter() which will give you something much
better than milliseconds.