14

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?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Yee Liu
  • 1,417
  • 3
  • 15
  • 17

2 Answers2

18

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.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
Marinos K
  • 1,779
  • 16
  • 39
4

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.

David
  • 27,652
  • 18
  • 89
  • 138
  • 6
    A better way than `ctime` to turn turn `system_clock::time_point` into a field date/time structure: http://howardhinnant.github.io/date_v2.html :-) – Howard Hinnant Mar 18 '16 at 22:49
  • 5
    @YeeLiu: `ctime` is not "type safe". For example `difftime` returns a `double` instead of a `duration`. And `tm.tm_sec` has type `int` instead of type `seconds`. This lack of type safety means that the compiler can't check logic errors which (for example) perform illogical algebra on units of time. – Howard Hinnant Mar 18 '16 at 22:53
  • @YeeLiu Also the fixed epoch can be a nuisance. Another is the total blindness to threads. Allow me to moderate the total blindness to extremely nearsighted. – user4581301 Mar 18 '16 at 22:54
  • Thank you so much for the explanation. Can you explain a little bit about blindness to threads ? – Yee Liu Mar 18 '16 at 22:59
  • @YeeLiu A critical function `localtime` is not reentrant. This function is essential to any calendering conversions from time points – Galik Mar 18 '16 at 23:02