Parsing time from C++ DLL to Matlab - c++

I'm writing a C++ DLL which will be accessed using MATLAB's loadlibrary. I need a specific function to return the current time in milliseconds precision, and parse it correctly in matlab. Specifically i'll need to extract the year, month, day, hours, minutes, seconds and milliseconds.
I currently have something like
long long time_since_epoch()
{
return std::chrono::system_clock::now().time_since_epoch().count();
}
which MATLAB calls using t = calllib('myDLL', 'time_since_epoch');.
Then I tried parsing it using dt = datetime(t, 'convertfrom', 'epochtime');, which didn't work.
But, I compared it with the time given from posixtime(datetime) and found out I'm getting a correct answer by using dt = datetime(t / 10000000, 'convertfrom', 'epochtime');, which is very odd.
I don't fully understand what's going on here, and I somehow lost the milliseconds in the process.

Your system_clock is not counting milliseconds, it is counting something finer than a millisecond. Exactly what isn't important because you can specifically ask for the count in milliseconds:
long long time_since_epoch()
{
using namespace std::chrono;
return time_point_cast<milliseconds>(system_clock::now()).time_since_epoch().count();
}

Related

How to get nanoseconds from boost::chrono::hight_resolution_clock::time_point?

I am new to boost and chrono. I am writing a logger that logs the timestamps of API calls, entry and exit. I tried using boost::xtime first, but it wasn't giving the high resolution value I needed. Hence was thinking about using Chrono. I declared a boost::chrono::hight_resolution_clock::time_stamp x; variable for getting the timestamp and assigned it to boost::chrono::hight_resolution_clock::now ();. Now, I need to get the nanoseconds from this variable and put it in my log file (thats the requirement). So I cast it boost::chrono::duration_cast (x). But it just wouldn't let me do that. It needs 2 parameters apparently, and I only have one. Is there a way to get around this?. Is it possible to create another time_stamp variable and assign zero to it and use that variable?. I tried assigning zero, but its not working. Kindly help me out.
Thanks,
Sam
If tagged c++11, any reason why not to use std::chrono?
// Using std::chrono
auto start = std::chrono::high_resolution_clock::now(); // start timer
/* do some work */
auto diff = std::chrono::high_resolution_clock::now() - start; // get difference
auto nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(diff);
std::cout << "it took: " << nsec.count() << " nanoseconds" << std::endl;
boost::chrono::duration_cast converts a duration into the specified units, but you've given it a boost::chrono::time_point, not a duration.
There's really no such thing as "the current time in nanoseconds". To get a duration, you need to specify the time since which you want to know how many nanoseconds have elapsed (an "epoch"). Different clocks will measure their time based on different epochs.
boost::chrono::system_clock (currently) uses the Unix epoch (midnight Jan 1, 1970) as its epoch, but it's not steady and it may not have the resolution you need (it's in nanoseconds on my Ubuntu box, but in 1/10,000,000ths of a second on my Windows box).
boost::chrono::high_resolution_clock uses boot up as its epoch, is steady, and measures time in nanoseconds on both boxes I tested on.
Boost also provides other clocks like process_cpu_clock that use other epochs and count in other units.
Thus you can get nanos since Jan 1, 1970 using system_clock, but it may not actually be nanosecond-accurate, and it may go backwards if the user changes the system time or the computer syncs with network time, or you can get nanos since some other point in time using high_resolution_clock.

Getting milliseconds accuracy current time in Qt

Qt documentation about QTime::currentTime() says :
Note that the accuracy depends on the accuracy of the underlying
operating system; not all systems provide 1-millisecond accuracy.
But is there any way to get this time with milliseconds accuracy in windows 7?
You can use QDateTime class and convert the current time with the appropriate format:
QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss,zzz")
where 'z' corresponds to miliseconds accuracy.
you can use the functionality provided by time.h header file in C/C++.
#include <time.h>
clock_t start, end;
double cpu_time_used;
int main()
{
start = clock();
/* Do the work. */
end = clock();
cpu_time_used = ((double)(end-start)/ CLOCKS_PER_SEC);
}
Timer resolution may vary on different platforms and readings may not be accurate. If you need to get high-resolution, accurate timestamps on Windows 7, it provides QPC API:
https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408%28v=vs.85%29.aspx
GetSystemTimePreciseAsFileTime is claimed to provide system time with <1us resolution.
But that's only about accurate timestamp. If you need to actually do something with 1 ms latency (ex. handle an event), you need a RTOS, not a desktop clunker.
One common way would be to scale up whatever you are doing and do it 10-100 times in a row, that way you would be able get a more accurate time reading of whatever you are doing, by dividing the result by 10-100.
But getting millisecond precise readings of your time is pretty much useless because you don't have 100% of the cpu time, which means that your readings will have much greater variance than just 1 millisecond if the OS gives another process computing time while you are doing your actions.

Timestamp in milliseconds gives me 10 digit in C++?

I am trying to retrieve Current Time in milliseconds using boost library.. Below is my code which I am using to get the current time in milliseconds.
boost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration duration( time.time_of_day() );
std::cout << duration.total_milliseconds() << std::endl;
uint64_t timestampInMilliseconds = duration.total_milliseconds() // will this work or not?
std::cout << timestampInMilliseconds << std::endl;
But this prints out in 10 digit which is like 17227676.. I am running my code on my ubuntu machine.. And I believe it is always 13 digit long value? Isn't so?
After computing the timestamp in milliseconds, I need to use below formula on that -
int end = (timestampInMilliseconds / (60 * 60 * 1000 * 24)) % 14
But somehow I am not sure whether timestampInMilliseconds which I am getting is right or not?
First of all should I be using boost::posix or not? I am assuming there might be some better way.. I am running code on my ubuntu machine..
Update:-
As this piece of bash script prints out timestampInMilliseconds which is of 13 digit..
date +%s%N | cut -b1-13
The problem here is that you use time_of_day() which returns (from this reference)
Get the time offset in the day.
So from the value you provided in the question I can deduce that you ran this program at 4:47 am.
Instead you might want to use e.g. the to_tm() to get a struct tm and construct your time in milliseconds from there.
Also note that the %s format to the date command (and the strftime function) is the number of seconds since the epoch, not the number of milliseconds.
If you look at the tm structure, you will see that it has the number of years (since 1900, so subtract 70 here), days into the year, and then hours,, minutes and seconds into the day. All these can be used to calculate the time in seconds easily.
And that in seconds is the problem here. If you look at e.g. the POSIX time function you see that
shall return the value of time in seconds since the Epoch
If you want an accurate millisecond resolution you simply can't use the ptime (where the p stands for POSIX). If you want millisecond resolution you either have to use e.g. system functions that returns the time in higher resolutions (like gettimeofday), or you can see e.g. this old SO answer.

Converting steady_clock::time_point to time_t

I'm using the steady_clock for saving the time stamp of some messages. For debug purpose is usefull to have the calendar (or something similar).
For other clocks ther's the static function to_time_t, but on GCC (MinGW 4.8.0) this function is not present.
Now i print something like:
Timestamp: 26735259098242
For timestamp i need a steady_clock so I cannot use system_clock or others.
Edit
The previous print is given from the time_since_epoch().count()
Assuming you need the steady behavior for internal calculations, and not for display, here's a function you can use to convert to time_t for display.
using std::chrono::steady_clock;
using std::chrono::system_clock;
time_t steady_clock_to_time_t( steady_clock::time_point t )
{
return system_clock::to_time_t(system_clock::now()
+ duration_cast<system_clock::duration>(t - steady_clock::now()));
}
If you need steady behavior for logging, you'd want to get one ( system_clock::now(), steady_clock::now() ) pair at startup and use that forever after.

Getting the current time (in milliseconds) from the system clock in Windows?

How can you obtain the system clock's current time of day (in milliseconds) in C++? This is a windows specific app.
The easiest (and most direct) way is to call GetSystemTimeAsFileTime(), which returns a FILETIME, a struct which stores the 64-bit number of 100-nanosecond intervals since midnight Jan 1, 1601.
At least at the time of Windows NT 3.1, 3.51, and 4.01, the GetSystemTimeAsFileTime() API was the fastest user-mode API able to retrieve the current time. It also offers the advantage (compared with GetSystemTime() -> SystemTimeToFileTime()) of being a single API call, that under normal circumstances cannot fail.
To convert a FILETIME ft_now; to a 64-bit integer named ll_now, use the following:
ll_now = (LONGLONG)ft_now.dwLowDateTime + ((LONGLONG)(ft_now.dwHighDateTime) << 32LL);
You can then divide by the number of 100-nanosecond intervals in a millisecond (10,000 of those) and you have milliseconds since the Win32 epoch.
To convert to the Unix epoch, subtract 116444736000000000LL to reach Jan 1, 1970.
You mentioned a desire to find the number of milliseconds into the current day. Because the Win32 epoch begins at a midnight, the number of milliseconds passed so far today can be calculated from the filetime with a modulus operation. Specifically, because there are 24 hours/day * 60 minutes/hour * 60 seconds/minute * 1000 milliseconds/second = 86,400,000 milliseconds/day, you could user the modulus of the system time in milliseconds modulus 86400000LL.
For a different application, one might not want to use the modulus. Especially if one is calculating elapsed times, one might have difficulties due to wrap-around at midnight. These difficulties are solvable, the best example I am aware is Linus Torvald's line in the Linux kernel which handles counter wrap around.
Keep in mind that the system time is returned as a UTC time (both in the case of GetSystemTimeAsFileTime() and simply GetSystemTime()). If you require the local time as configured by the Administrator, then you could use GetLocalTime().
To get the time expressed as UTC, use GetSystemTime in the Win32 API.
SYSTEMTIME st;
GetSystemTime(&st);
SYSTEMTIME is documented as having these relevant members:
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
As shf301 helpfully points out below, GetLocalTime (with the same prototype) will yield a time corrected to the user's current timezone.
You have a few good answers here, depending on what you're after. If you're looking for just time of day, my answer is the best approach -- if you need solid dates for arithmetic, consider Alex's. There's a lot of ways to skin the time cat on Windows, and some of them are more accurate than others (and nobody has mentioned QueryPerformanceCounter yet).
A cut-to-the-chase example of Jed's answer above:
const std::string currentDateTime() {
SYSTEMTIME st, lt;
GetSystemTime(&st);
char currentTime[84] = "";
sprintf(currentTime,"%d/%d/%d %d:%d:%d %d",st.wDay,st.wMonth,st.wYear, st.wHour, st.wMinute, st.wSecond , st.wMilliseconds);
return string(currentTime); }
Use GetSystemTime, first; then, if you need that, you can call SystemTimeToFileTime on the SYSTEMTIME structure that the former fills for you. A FILETIME is a 64-bit count of 100-nanosecs intervals since an epoch, and so more suitable for arithmetic; a SYSTEMTIME is a structure with all the expected fields (year, month, day, hour, etc, down to milliseconds). If you want to know "how many milliseconds have elapsed since midnight", for example, subtracting two FILETIME structures (one for the current time, one obtained by converting the same SYSTEMTIME after zeroing out the appropriate fields) and dividing by the appropriate power of ten is probably the simplest available approach.
Depending on the needs of your application there are six common options. This Dr Dobbs Journal article will give you all the information (and more) you need on choosing the best one.
In your specific case, from this article:
GetSystemTime() retrieves the current
system time and instantiates a
SYSTEMTIME structure, which is
composed of a number of separate
fields including year, month, day,
hours, minutes, seconds, and
milliseconds.
Here is some code that works in Windows which I've used in a Open Watcom C project. It should work in C++ It returns seconds (not milliseconds) using _dos_gettime or gettime
double seconds(void)
{
#ifdef __WATCOMC__
struct dostime_t t;
_dos_gettime(&t);
return ((double)t.hour * 3600 + (double)t.minute * 60 + (double)t.second + (double)t.hsecond * 0.01);
#else
struct time t;
gettime(&t);
return ((double)t.ti_hour * 3600 + (double)t.ti_min * 60 + (double)t.ti_sec + (double)t.ti_hund * 0.01);
#endif
}
While it's not what the question asks, it's worth considering why you want this info.
If all you want to do is keep track of how long something takes to calculate or the time past since the last user interaction, consider using the uptime (milliseconds since boot), which is much simpler to get: GetTickCount() or GetTickCount64(). This is all I wanted to do but I went down the epoch rabbit hole first because that's how you do it under unix.