Skip to content

Commit 971eada

Browse files
MaskRaycopybara-github
authored andcommitted
Decrease the precision of absl::Now in x86-64 debug builds
CycleClock::Now utilizes ABSL_INTERNAL_CYCLECLOCK_SHIFT to discourage reliance on the raw CPU cycle counter values. As a side effect, it discourages strictly-increasing assumption. Apply the idea to discourage over-reliance on the precision of absl::Now/absl::GetCurrentTimeNanos. Programs relying on a very high precision often exhibit portability issues on machines with a lower cycle counter precision, or worse, race conditions. For example, Apple M1 emulated x86 RDTSC only guarantees weakly-increasing RDTSC values. x86 clock speed is usually measured in GHz and is still precise after we drop 8 least significant bits. PiperOrigin-RevId: 603493500 Change-Id: Ib1b00075109283f5dbcb39a43fe0ab722351a1e2
1 parent 7339447 commit 971eada

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

absl/time/clock.cc

+15-1
Original file line numberDiff line numberDiff line change
@@ -88,11 +88,25 @@ ABSL_NAMESPACE_END
8888
namespace absl {
8989
ABSL_NAMESPACE_BEGIN
9090
namespace time_internal {
91+
92+
// On some processors, consecutive reads of the cycle counter may yield the
93+
// same value (weakly-increasing). In debug mode, clear the least significant
94+
// bits to discourage depending on a strictly-increasing Now() value.
95+
// In x86-64's debug mode, discourage depending on a strictly-increasing Now()
96+
// value.
97+
#if !defined(NDEBUG) && defined(__x86_64__)
98+
constexpr int64_t kCycleClockNowMask = ~int64_t{0xff};
99+
#else
100+
constexpr int64_t kCycleClockNowMask = ~int64_t{0};
101+
#endif
102+
91103
// This is a friend wrapper around UnscaledCycleClock::Now()
92104
// (needed to access UnscaledCycleClock).
93105
class UnscaledCycleClockWrapperForGetCurrentTime {
94106
public:
95-
static int64_t Now() { return base_internal::UnscaledCycleClock::Now(); }
107+
static int64_t Now() {
108+
return base_internal::UnscaledCycleClock::Now() & kCycleClockNowMask;
109+
}
96110
};
97111
} // namespace time_internal
98112

0 commit comments

Comments
 (0)