approx_time.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file approx_time.c
  7. * \brief Cache the last result of time(), for performance and testing.
  8. **/
  9. #include "orconfig.h"
  10. #include "lib/subsys/subsys.h"
  11. #include "lib/wallclock/approx_time.h"
  12. #include "lib/wallclock/wallclock_sys.h"
  13. /* =====
  14. * Cached time
  15. * ===== */
  16. #ifndef TIME_IS_FAST
  17. /** Cached estimate of the current time. Updated around once per second;
  18. * may be a few seconds off if we are really busy. This is a hack to avoid
  19. * calling time(NULL) (which not everybody has optimized) on critical paths.
  20. */
  21. static time_t cached_approx_time = 0;
  22. /** Return a cached estimate of the current time from when
  23. * update_approx_time() was last called. This is a hack to avoid calling
  24. * time(NULL) on critical paths: please do not even think of calling it
  25. * anywhere else. */
  26. time_t
  27. approx_time(void)
  28. {
  29. return cached_approx_time;
  30. }
  31. /** Update the cached estimate of the current time. This function SHOULD be
  32. * called once per second, and MUST be called before the first call to
  33. * get_approx_time. */
  34. void
  35. update_approx_time(time_t now)
  36. {
  37. cached_approx_time = now;
  38. }
  39. #endif /* !defined(TIME_IS_FAST) */
  40. static int
  41. subsys_wallclock_initialize(void)
  42. {
  43. update_approx_time(time(NULL));
  44. return 0;
  45. }
  46. const subsys_fns_t sys_wallclock = {
  47. .name = "wallclock",
  48. .supported = true,
  49. /* Approximate time is a diagnostic feature, we want it to init right after
  50. * low-level error handling. */
  51. .level = -98,
  52. .initialize = subsys_wallclock_initialize,
  53. };