Why does difference in two chrono time points result in seconds? - c++

I have the following code:
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
using namespace std;
using namespace std::chrono;
int main()
{
using my_timepoint = time_point<high_resolution_clock, nanoseconds>;
my_timepoint now = system_clock::now();
my_timepoint then = system_clock::now() - seconds{1};
duration<double> my_dur = now - then;
cout << my_dur.count();
}
Here my_timepoint is expressed in nanoseconds still I get output of this code as 1. Why is it not 1e+09? How does the difference in two time points evaluated?

The duration template takes a ratio argument as described here:
https://en.cppreference.com/w/cpp/chrono/duration
The code posted is using the default value (1 tick every 1 second), so naturally when you ask it for count(), it will return just 1, to represent the number of ticks that have elapsed.
You can construct a duration object that uses a different ratio, then you'll get 1e+09:
duration<double, std::ratio<1, 1000000000>> my_dur = now - then;

Related

is there a way to get utc nanoseconds for a date in uint64_t in c++

I want to get number of nano seconds since epoch in uint64_t for a particular date, is there a function in any c++ library to get it.
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()
);
You could use Howard Hinnant's free, open-source date/time library which extends std::chrono into the real of calendars:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono_literals;
uint64_t k = (sys_days{2017_y/mar/21} + 10h + 27min + 5s +
123456789ns).time_since_epoch().count();
std::cout << k << '\n';
}
Output:
1490092025123456789

File name as current time in seconds since the epoch in c++

I want to create a new file in c++ having file name as seconds (current time in seconds since the epoch) in FILE_FOLDER.
How can I modify the statement
myfile.open("/FILE_FOLDER/seconds");
Getting the seconds since the epoch as a string is fairly easy:
#include <chrono>
#include <string>
auto now = std::chrono::system_clock::now();
auto now_sec = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());
auto now_sec_str = std::to_string(now_sec.count());
Or simply:
#include <ctime>
#include <string>
auto now_sec_str = std::to_string(long(std::time(nullptr)));
Then just append that to your folder name:
myfile.open("/FILE_FOLDER/" + now_sec_str);

How to get UTC seconds since epoch till midnight

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().

How to get timestamp in microseconds in C++?

I have tried this and other codes I found online but they did not work. My IDE is Xcode.
Edit: When I tried the code on the link, the variable long long microseconds always returned 0.
I would like to print the timestamp in this manner: (hour:minute:microseconds). For example, 15:17:09:134613464312.
The method you use is correct.
If you the code between the two now() calls lasts less than a microseconds, microseconds will always be zero, since the number is not a floating point. If you have always zero, that means you need higher resolution (try nanoseconds).
Btw, if you simply want timestamp, you don't want to use this code since it is done to compute elapsed time between two time points. You can try something like this:
auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>
(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
Which is really a timestamp and not a duration.
EDIT: To have the current microseconds count, you can do something like this:
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
using namespace std::chrono;
using days = duration<int, ratio_multiply<hours::period, ratio<24> >::type>;
int main() {
system_clock::time_point now = system_clock::now();
system_clock::duration tp = now.time_since_epoch();
days d = duration_cast<days>(tp);
tp -= d;
hours h = duration_cast<hours>(tp);
tp -= h;
minutes m = duration_cast<minutes>(tp);
tp -= m;
seconds s = duration_cast<seconds>(tp);
tp -= s;
cout << tp.count() << "\n";
return 0;
}
This will print the current microseconds count.
Hours:Minutes:Seconds is pretty easy.

How to sleep until next Sunday

How can I sleep until next Sunday using boost? Can i convert boost::gregorian::date object to something that boost::this_thread::sleep_until can handle? Is it possible?
#include <boost/date_time.hpp>
int main()
{
boost::gregorian::date current_date(boost::gregorian::day_clock::local_day());
boost::gregorian::greg_weekday next_sunday_date(boost::gregorian::Sunday);
boost::gregorian::date next_weekday_date = next_weekday(current_date, next_sunday_date);
// ...
}
Here's what I came up with.
Note that I made the code generally more readable. This is important, not just for future maintenance, but also because it will allow you to "see the forest for the trees" - in turn allowing you to remember the important concepts mentally.
At least, that helps me.
Edit DyP contributed a way to use sleep_until (which would behave more accurately in rare circumstances, e.g. where the clock would change during the sleep).
#include <boost/date_time.hpp>
#include <boost/date_time/time_clock.hpp>
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
using namespace boost::gregorian;
using boost::posix_time::ptime;
using clock = boost::posix_time::microsec_clock; // or: boost::posix_time::second_clock;
auto today = date(day_clock::local_day());
auto at_sunday = greg_weekday(Sunday);
auto next_sunday = next_weekday(today, at_sunday);
#if 1
auto as_tm = to_tm(next_sunday);
auto as_time_t = mktime(&as_tm);
auto as_time_point = std::chrono::system_clock::from_time_t(as_time_t);
std::this_thread::sleep_until(as_time_point);
#else
auto duration = (ptime(next_sunday) - clock::local_time());
auto msecs = duration.total_milliseconds();
std::cout << msecs << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(msecs));
#endif
}
See it compiling on Coliru (obviously times out)
This sounds unstable. What if the user turns the computer off or goes into hibernation, or just does a restart?
I would do this in one of two ways:
Add a scheduled task(or whatever the windows/osx terminology is) / cronjob (linux) and set it to run on Sunday.
Add it to autostart and periodically(once per 10/30/60 minutes) check if it's Sunday.
Both ways handle restart/shut off/hibernation better than sleeping for 5 days.