Reputation: 4083
I'm developping c++11 project in linux. And now I have some requirements for time library.
I want to use time for ...
Recently I found std::chrono and its comparing functions are really useful. On the other hand, I know some legacy libraries like time.h. In my case, what's the best time library? I want to choose the best time library.
Upvotes: 2
Views: 2554
Reputation: 219255
Layered on top of <chrono>
with more calendrical computations and niceties is this free, open source, date time library which you might find useful.
- time stamp for access logs
- human friendly logs, like "2014/01/3/18:32:32"
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << format("%Y/%m/%d %T\n", floor<seconds>(system_clock::now()));
}
Which output for me just now:
2017/07/08 18:00:19
- compare time by second between last access and current access
auto last_access = floor<seconds>(system_clock::now());
// ...
auto current_access = floor<seconds>(system_clock::now());
if (current_access > last_access)
// ...
- easy to convert, utc <-> epoc
auto now = floor<seconds>(system_clock::now());
cout << format("%F %T %Z", now) << '\n';
cout << now.time_since_epoch() << '\n';
Output:
2017-07-08 18:06:53 UTC
1499537213s
Oh, and heads up, Unix Time 1.5 billion seconds is right around the corner:
cout << format("%F %T %Z\n", sys_seconds{1'500'000'000s});
2017-07-14 02:40:00 UTC
This library is now part of C++20. The result is that <chrono>
now has a superset of the functionality contained in <time.h>
.
MSVS has a complete implementation. Work is underway to ship this with gcc and llvm toolsets.
Upvotes: 6
Reputation: 54689
std::chrono
offers a bunch of advantages over the legacy timer libraries:
std::steady_clock
are hard to achieve with just the legacy API without resorting to platform-specific solutions.The big drawback to look out for is that, due to the fact that chrono is a relatively young library, implementations are more likely to contain bugs. I personally ran into a couple of small issues with both the Boost and the Visual C++ 2012 implementation of chrono and while none of those were critical, they weren't exactly pleasant to deal with.
Also note that chrono explicitly excludes any functionality regarding dates and calendars. For this functionality interop with the C API is offered.
Personal advice: Overall the differences between the APIs are not that dramatic. The simple use cases that you listed should be reasonably easy to implement with both APIs, so I'd suggest you stick with the one that fits best with the surrounding code base: If you are writing in a modern C++ style, that is not afraid of templates and complex types, you will feel right at home with chrono. If on the other hand, your code is closer to the design of the C-based POSIX APIs, time.h
would probably be a better fit.
Upvotes: 5