From 2171293fe73e3b08e8aff2af70758e2c5dcdf4d7 Mon Sep 17 00:00:00 2001 From: Lucian Grijincu Date: Wed, 16 Sep 2015 20:20:29 -0700 Subject: [PATCH] folly: clock: remove static globals, replace with meyers singleton Reviewed By: @yfeldblum Differential Revision: D2446000 --- folly/detail/Clock.cpp | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/folly/detail/Clock.cpp b/folly/detail/Clock.cpp index 855645c4..7a6c8b28 100644 --- a/folly/detail/Clock.cpp +++ b/folly/detail/Clock.cpp @@ -20,17 +20,27 @@ #include #include -static mach_timebase_info_data_t tb_info; -static bool tb_init = mach_timebase_info(&tb_info) == KERN_SUCCESS; +namespace { + +const mach_timebase_info_data_t* tbInfo() { + static auto info = [] { + static mach_timebase_info_data_t info; + return (mach_timebase_info(&info) == KERN_SUCCESS) ? &info : nullptr; + }(); + return info; +}; + +} // anonymous namespace int clock_gettime(clockid_t clk_id, struct timespec* ts) { - if (!tb_init) { + auto tb_info = tbInfo(); + if (tb_info == nullptr) { errno = EINVAL; return -1; } uint64_t now_ticks = mach_absolute_time(); - uint64_t now_ns = (now_ticks * tb_info.numer) / tb_info.denom; + uint64_t now_ns = (now_ticks * tb_info->numer) / tb_info->denom; ts->tv_sec = now_ns / 1000000000; ts->tv_nsec = now_ns % 1000000000; @@ -38,13 +48,14 @@ int clock_gettime(clockid_t clk_id, struct timespec* ts) { } int clock_getres(clockid_t clk_id, struct timespec* ts) { - if (!tb_init) { + auto tb_info = tbInfo(); + if (tb_info == nullptr) { errno = EINVAL; return -1; } ts->tv_sec = 0; - ts->tv_nsec = tb_info.numer / tb_info.denom; + ts->tv_nsec = tb_info->numer / tb_info->denom; return 0; } -- 2.34.1