Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between <chrono> and <ctime>?

For measuring execution time of a function, I can use both. But what is the difference between using <chrono> and <ctime>? Should I prefer one instead of another?

like image 338
Yee Liu Avatar asked Mar 18 '16 22:03

Yee Liu


People also ask

What is Chrono time?

Chronos time is how we measure our days and our lives quantitatively.

What is Chrono library?

Chrono library in C++ This Chrono library is used for date and time. Timers and clocks are different in different systems. So if we want to improve time over precision we can use this library. In this library, it provides precision-neutral concept, by separating the durations and point of time.


2 Answers

ctime is a C-style header, it's old, not type safe and not as accurate as chrono. chrono is the preferred option in C++; it's a contemporary C++ header, it's type safe, as accurate as our hardware allows, it has extended functionality, and, more importantly, it follows C++ (rather than C) logic so that certain things will be more natural/expressive with it and so that we may expect it to be aware of many contemporary language features (threads, exceptions, etc) - we cannot make the same assumptions for ctime.

That said, there are still several use-cases for ctime (or even time.h), e.g. when we need to talk with some C API or when we rely on old code-bases or when we use some library which follows a different kind of logic. C++ is designed to be pragmatic and not to be "pure" in any respect; this is why ctime and all sorts of antiquated headers, syntaxes and language features are still there even if programers are discouraged from using them.

like image 133
Marinos K Avatar answered Sep 17 '22 14:09

Marinos K


ctime is old school. Its only use now is as a crap solution to getting dates from time points (since c++ doesn't have an adequate standard datetime library). For general time needs, use chrono. If you need to turn a system_clock::time_point into a date/time, use ctime.

like image 33
David Avatar answered Sep 19 '22 14:09

David