Storing a time_point outside of the application - c++11

I am using an std::chrono::system_clock::time_point in my program.
When the application stops I want to save to the time_point to a file and load it again when the application starts.
If it was an UNIX-Timestamp I could simply store the value as integer. Is there a way to similarly store a time_point?

Yes. Choose the precision you desire the timestamp in (seconds, milliseconds, ... nanoseconds). Then cast the system_clock::time_point to that precision, extract its numeric value, and print it:
cout << time_point_cast<seconds>(system_clock::now()).time_since_epoch().count();
Though not specified by the standard, the above line (de facto) portably outputs the number of non-leap seconds since 1970-01-01 00:00:00 UTC. That is, this is a UNIX-Timestamp.
I am attempting to get the above code blessed by the standard to do what it in fact does by all implementations today. And I have the unofficial assurance of the std::chrono implementors, that they will not change their system_clock epochs in the meantime.
Here's a complete roundtrip example:
#include <chrono>
#include <iostream>
#include <sstream>
int
main()
{
using namespace std;
using namespace std::chrono;
stringstream io;
io << time_point_cast<seconds>(system_clock::now()).time_since_epoch().count();
int64_t i;
system_clock::time_point tp;
io >> i;
if (!io.fail())
tp = system_clock::time_point{seconds{i}};
}

Related

How do I instantiate a boost::date_time::time_duration with nanoseconds?

I feel like I'm missing something obvious here. I can easily make a time_duration with milliseconds, microseconds, or seconds by doing:
time_duration t1 = seconds(1);
time_duration t2 = milliseconds(1000);
time_duration t3 = microseconds(1000000);
But there's no function for nanoseconds. What's the trick to converting a plain integer nanoseconds value to a time_duration?
I'm on amd64 architecture on Debian Linux. Boost version 1.55.
boost::posix_time::microseconds is actually subsecond_duration<boost::posix_time::time_duration, 1000000>. So...
#include <boost/date_time/posix_time/posix_time.hpp>
using nanoseconds = boost::date_time::subsecond_duration<boost::posix_time::time_duration, 1000000000>;
int main() {
boost::posix_time::time_duration t = nanoseconds(1000000000);
std::cout << t << "\n";
}
Prints
00:00:01
UPDATE
Indeed, in the Compile Options for the Boost DateTime library you can see that there's an option to select nanosecond resolution:
By default the posix_time system uses a single 64 bit integer
internally to provide a microsecond level resolution. As an
alternative, a combination of a 64 bit integer and a 32 bit integer
(96 bit resolution) can be used to provide nano-second level
resolutions. The default implementation may provide better performance
and more compact memory usage for many applications that do not
require nano-second resolutions.
To use the alternate resolution (96 bit nanosecond) the variable
BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG must be defined in the library
users project files (ie Makefile, Jamfile, etc). This macro is not
used by the Gregorian system and therefore has no effect when building
the library.
Indeed, you can check it using:
Live On Coliru
#define BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG
#include <boost/date_time/posix_time/posix_time.hpp>
int main() {
using namespace boost::posix_time;
std::cout << nanoseconds(1000000000) << "\n";
}

How to use PAPI with C++11 std:thread?

I would like to use PAPI to get the overall counters of all C++11 std::thread threads in a program.
PAPI documentation on Threads says that:
Thread support in the PAPI library can be initialized by calling the following low-level function in C: int PAPI_thread_init(unsigned long(*handle)(void));
where the handle is a
Pointer to a routine that returns the current thread ID as an unsigned long.
For example, for pthreads the handle is pthread_self.
But, I have no idea what it should be with C++11 std::thread.
Nor if it makes more sense to use something different from PAPI.
C++11 threading support has the std::this_thread::get_id() function that returns a std::thread::id instance which can be serialized to a stream. Then you coud try to read an unsigned long from the stream and return ir. Something like this:
#include <thread>
#include <iostream>
#include <sstream>
unsigned long current_thread_id()
{
std::stringstream id_stream;
id_stream << std::this_thread::get_id();
unsigned long id;
id_stream >> id;
return id;
}
int main(int argc, char** argv)
{
std::cout << current_thread_id();
return 0;
}
So in this snippet the current_thread_id function is what you are looking for, but you should add proper error handling (the thread id may not always be a number, in that case you will not be able to read a number from the stream and you should handle that accordingly).
That being said, maybe just use GetCurrentThreadId , since you are already introducing the Linux specific pthread_self.

chrono C++11 version of matlabs datenum

Is there a C++11 version of matlabs datenum function in #include<chrono>?
I already know it exists in boost thanks to this post
No, there is not. However here is a "how-to" manual for how to write the algorithms for your chrono-compatible date library. Using these algorithms, I can easily, for example, do this:
#include "../date_performance/date_algorithms"
#include <ratio>
#include <chrono>
#include <iostream>
typedef std::chrono::duration
<
int,
std::ratio_multiply<std::ratio<24>, std::chrono::hours::period>
> days;
typedef std::chrono::time_point<std::chrono::system_clock, days> date_point;
int
main()
{
using namespace std::chrono;
date_point datenum{days{days_from_civil(2014, 2, 5)}};
auto d = system_clock::now() - datenum;
auto h = duration_cast<hours>(d);
d -= h;
auto m = duration_cast<minutes>(d);
std::cout << "The current UTC time is " << h.count() << ':' << m.count() << '\n';
date_point datenum2{days{days_from_civil(2014, 3, 5)}};
std::cout << "There are " << (datenum2-datenum).count() << " days between 2014-03-05 and 2014-02-05\n";
}
Which for me outputs:
The current UTC time is 22:12
There are 28 days between 2014-03-05 and 2014-02-05
The first thing you need to do is create a chrono::duration to represent a day, named days above. Then it is handy to create a chrono::time_point based on the days duration. This time_point is compatible with every known implementation of system_clock::time_point. I.e. you can subtract them.
In this duration I subtract now() from the current date to get the hours::minutes of the day in the UTC timezone. I also demonstrate how to compute the number of days between any two dates.
Feel free to use these algorithms, and perhaps wrap all of this up in a type-safe date class. The link only provides the algorithms, and not an actual date class.
I might post a date class based on these algorithms in the future if I get the time...
I don't know what matlabs datenum is but here is how to do basically the same as the accepted answer of the question you link to, that is arithmetic with time points and durations but in C++11 without boost:
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
int main() {
duration<long> one_day{ hours(24) };
system_clock::time_point now = system_clock::now();
system_clock::time_point tomorrow = now + one_day;
time_t t = system_clock::to_time_t(tomorrow);
cout << "Tomorrow: " << ctime(&t) << '\n';
}
Hope this helps.

Retrieving boot time using GetTickCount64

I'm trying to extract boot time by getting current time SYSTEMTIME structure, then converting it to FILETIME which I then convert to ULARGE_INTEGER from which I subtract GetTickCount64() and then proceed on converting everything back to SYSTEMTIME.
I'm comparing this function to 'NET STATISTICS WORKSTATION' and for some reason my output is off by several hours, which don't seem to match any timezone differences.
Here's visual studio example code:
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#define KILOBYTE 1024
#define BUFF KILOBYTE
int _tmain(int argc, _TCHAR* argv[])
{
ULARGE_INTEGER ticks, ftime;
SYSTEMTIME current, final;
FILETIME ft, fout;
OSVERSIONINFOEX osvi;
char output[BUFF];
int retval=0;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
ZeroMemory(&final, sizeof(SYSTEMTIME));
GetVersionEx((OSVERSIONINFO *) &osvi);
if (osvi.dwBuildNumber >= 6000) ticks.QuadPart = GetTickCount64();
else ticks.QuadPart = GetTickCount();
//Convert miliseconds to 100-nanosecond time intervals
ticks.QuadPart = ticks.QuadPart * 10000;
//GetLocalTime(&current); -- //doesn't really fix the problem
GetSystemTime(&current);
SystemTimeToFileTime(&current, &ft);
printf("INITIAL: Filetime lowdatetime %u, highdatetime %u\r\n", ft.dwLowDateTime, ft.dwHighDateTime);
ftime.LowPart=ft.dwLowDateTime;
ftime.HighPart=ft.dwHighDateTime;
//subtract boot time interval from current time
ftime.QuadPart = ftime.QuadPart - ticks.QuadPart;
//Convert ULARGE_INT back to FILETIME
fout.dwLowDateTime = ftime.LowPart;
fout.dwHighDateTime = ftime.HighPart;
printf("FINAL: Filetime lowdatetime %u, highdatetime %u\r\n", fout.dwLowDateTime, fout.dwHighDateTime);
//Convert FILETIME back to system time
retval = FileTimeToSystemTime(&fout, &final);
printf("Return value is %d\r\n", retval);
printf("Current time %d-%.2d-%.2d %.2d:%.2d:%.2d\r\n", current.wYear, current.wMonth, current.wDay, current.wHour, current.wMinute, current.wSecond);
printf("Return time %d-%.2d-%.2d %.2d:%.2d:%.2d\r\n", final.wYear, final.wMonth, final.wDay, final.wHour, final.wMinute, final.wSecond);
return 0;
}
I ran it and found that it works correctly when using GetLocalTime as opposed to GetSystemTime, which is expressed in UTC. So it would make sense that GetSystemTime would not necessarily match the "clock" on the PC.
Other than that, though, the issue could possibly be the call to GetVersionEx. As written, I think it will always return zeros for all values. You need this line prior to calling it:
osvi.dwOSVersionInfoSize = sizeof( osvi );
Otherwise that dwBuildNumber will be zero and it will call GetTickCount, which is only good for 49 days or so. On the other hand, if that were the case, I think you would get a result with a much larger difference.
I'm not completely sure that (as written) the check is necessary to choose which tick count function to call. If GetTickCount64 doesn't exist, the app would not load due to the missing entrypoint (unless perhaps delay loading was used ... I'm not sure in that case). I believe that it would be necessary to use LoadLibrary and GetProcAddress to make the decision dynamically between those two functions and have it work on an older platform.

Getting System Date in MSVC 6.0

I am trying to get system date in a C program on a MSVC++ 6.0 compiler. I am using a system call:
system("date /T") (output is e.g. 13-Oct-08 which is date on my system in the format i have set)
but this prints the date to the i/o console.
How do i make take this date as returned by above system call and store it as a string value to a string defined in my code?
Or
Is there any other API i can use to get the date in above mentioned format (13-Oct-08, or 13-10-08) ?
-AD
#include <windows.h>
#include <iostream>
int main() {
SYSTEMTIME systmDateTime = {};
::GetLocalTime(&systmDateTime);
wchar_t wszDate[64] = {};
int const result = ::GetDateFormatW(
LOCALE_USER_DEFAULT, DATE_SHORTDATE,
&systmDateTime, 0, wszDate, _countof(wszDate));
if (result) {
std::wcout << wszDate;
}
}
There are a couple of ways to do this using API functions, two that jump to mind are strftime and GetDateFormat.
I'd like to provide examples but I'm afraid I don't have a Win32 compiler handy at the moment. Hopefully the examples in the above documentation are sufficient.
Have a read of Win32 Time functions; GetLocalTime may be your friend. There are also the standard C time functions, time and strftime.
For future reference, in a C program, it is almost always the wrong answer to invoke an external utility and capture it's STDOUT.
Thanks for the pointers.
I used this and it served my purpose:
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/timeb.h>
#include <string.h>
int main()
{
char tmpbuf[128];
time_t ltime;
struct tm *today;
_strdate( tmpbuf );
printf("\n before formatting date is %s",tmpbuf);
time(&ltime);
today = localtime( &ltime );
strftime(tmpbuf,128,"%d-%m-%y",today);
printf( "\nafter formatting date is %s\n", tmpbuf );
}
-AD

Resources