Commit cb6f1ec6 authored by Peter Kasting's avatar Peter Kasting Committed by Commit Bot

[Reland] //base/time cleanups:

* Make more things constexpr and/or make it possible to do so later
* Inline SaturatedAdd/Sub(), FromDouble(), FromProduct()
* Order the FromUnits{,D}() pairs together
* Init members in declaration
* Briefer implementations of various functions
* IWYU
* Fix declared-but-not-defined issue for FromTimeSpec() w/OS_FUSCHIA
* Use more specific DCHECKs
* No else after return
* Omit needless qualifiers
* EXPECT -> static_assert where possible
* <atomic> is legal now
* Don't handle DCHECK failure

The inlines don't hurt size: this saves 4 KB off chrome.dll in my local
release build.

First landed as r799459, reverted due to test flakiness.

Bug: none
Change-Id: I385263d97494946e1693062063cb27f7e0ea9f7f
TBR: stevenjb, tsepez
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2365092Reviewed-by: default avatarYuri Wiitala <miu@chromium.org>
Reviewed-by: default avatarPeter Kasting <pkasting@chromium.org>
Commit-Queue: Peter Kasting <pkasting@chromium.org>
Cr-Commit-Position: refs/heads/master@{#799966}
parent d22e3d95
......@@ -30,7 +30,7 @@ namespace internal {
#if !BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
template <typename Dst, typename Src>
struct SaturateFastAsmOp {
static const bool is_supported = false;
static constexpr bool is_supported = false;
static constexpr Dst Do(Src) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<Dst>();
......@@ -43,7 +43,7 @@ struct SaturateFastAsmOp {
// eke out better performance than range checking.
template <typename Dst, typename Src, typename Enable = void>
struct IsValueInRangeFastOp {
static const bool is_supported = false;
static constexpr bool is_supported = false;
static constexpr bool Do(Src value) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<bool>();
......@@ -59,7 +59,7 @@ struct IsValueInRangeFastOp<
std::is_integral<Dst>::value && std::is_integral<Src>::value &&
std::is_signed<Dst>::value && std::is_signed<Src>::value &&
!IsTypeInRangeForNumericType<Dst, Src>::value>::type> {
static const bool is_supported = true;
static constexpr bool is_supported = true;
static constexpr bool Do(Src value) {
// Just downcast to the smaller type, sign extend it back to the original
......@@ -77,7 +77,7 @@ struct IsValueInRangeFastOp<
std::is_integral<Dst>::value && std::is_integral<Src>::value &&
!std::is_signed<Dst>::value && std::is_signed<Src>::value &&
!IsTypeInRangeForNumericType<Dst, Src>::value>::type> {
static const bool is_supported = true;
static constexpr bool is_supported = true;
static constexpr bool Do(Src value) {
// We cast a signed as unsigned to overflow negative values to the top,
......@@ -156,7 +156,7 @@ constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) {
// Arm, we can use the optimized saturation instructions.
template <typename Dst, typename Src, typename Enable = void>
struct SaturateFastOp {
static const bool is_supported = false;
static constexpr bool is_supported = false;
static constexpr Dst Do(Src value) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<Dst>();
......@@ -170,7 +170,7 @@ struct SaturateFastOp<
typename std::enable_if<std::is_integral<Src>::value &&
std::is_integral<Dst>::value &&
SaturateFastAsmOp<Dst, Src>::is_supported>::type> {
static const bool is_supported = true;
static constexpr bool is_supported = true;
static constexpr Dst Do(Src value) { return SaturateFastAsmOp<Dst, Src>::Do(value); }
};
......@@ -181,12 +181,12 @@ struct SaturateFastOp<
typename std::enable_if<std::is_integral<Src>::value &&
std::is_integral<Dst>::value &&
!SaturateFastAsmOp<Dst, Src>::is_supported>::type> {
static const bool is_supported = true;
static constexpr bool is_supported = true;
static constexpr Dst Do(Src value) {
// The exact order of the following is structured to hit the correct
// optimization heuristics across compilers. Do not change without
// checking the emitted code.
Dst saturated = CommonMaxOrMin<Dst, Src>(
const Dst saturated = CommonMaxOrMin<Dst, Src>(
IsMaxInRangeForNumericType<Dst, Src>() ||
(!IsMinInRangeForNumericType<Dst, Src>() && IsValueNegative(value)));
return BASE_NUMERICS_LIKELY(IsValueInRangeForNumericType<Dst>(value))
......@@ -241,7 +241,7 @@ constexpr Dst strict_cast(Src value) {
// Some wrappers to statically check that a type is in range.
template <typename Dst, typename Src, class Enable = void>
struct IsNumericRangeContained {
static const bool value = false;
static constexpr bool value = false;
};
template <typename Dst, typename Src>
......@@ -250,8 +250,9 @@ struct IsNumericRangeContained<
Src,
typename std::enable_if<ArithmeticOrUnderlyingEnum<Dst>::value &&
ArithmeticOrUnderlyingEnum<Src>::value>::type> {
static const bool value = StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
NUMERIC_RANGE_CONTAINED;
static constexpr bool value =
StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
NUMERIC_RANGE_CONTAINED;
};
// StrictNumeric implements compile time range checking between numeric types by
......
This diff is collapsed.
This diff is collapsed.
......@@ -33,7 +33,7 @@ Time TimeNowFromSystemTimeIgnoringOverride() {
namespace subtle {
TimeTicks TimeTicksNowIgnoringOverride() {
const zx_time_t nanos_since_boot = zx_clock_get_monotonic();
CHECK(nanos_since_boot != 0);
CHECK_NE(0, nanos_since_boot);
return TimeTicks::FromZxTime(nanos_since_boot);
}
} // namespace subtle
......@@ -49,11 +49,11 @@ zx_duration_t TimeDelta::ToZxDuration() const {
// static
Time Time::FromZxTime(zx_time_t nanos_since_unix_epoch) {
return Time::UnixEpoch() + TimeDelta::FromNanoseconds(nanos_since_unix_epoch);
return UnixEpoch() + TimeDelta::FromNanoseconds(nanos_since_unix_epoch);
}
zx_time_t Time::ToZxTime() const {
return (*this - Time::UnixEpoch()).InNanoseconds();
return (*this - UnixEpoch()).InNanoseconds();
}
// static
......
......@@ -156,11 +156,10 @@ Time Time::FromCFAbsoluteTime(CFAbsoluteTime t) {
"CFAbsoluteTime must have an infinity value");
if (t == 0)
return Time(); // Consider 0 as a null Time.
if (t == std::numeric_limits<CFAbsoluteTime>::infinity())
return Max();
return Time(static_cast<int64_t>((t + kCFAbsoluteTimeIntervalSince1970) *
kMicrosecondsPerSecond) +
kTimeTToMicrosecondsOffset);
return (t == std::numeric_limits<CFAbsoluteTime>::infinity())
? Max()
: (UnixEpoch() + TimeDelta::FromSecondsD(double{
t + kCFAbsoluteTimeIntervalSince1970}));
}
CFAbsoluteTime Time::ToCFAbsoluteTime() const {
......@@ -168,11 +167,9 @@ CFAbsoluteTime Time::ToCFAbsoluteTime() const {
"CFAbsoluteTime must have an infinity value");
if (is_null())
return 0; // Consider 0 as a null Time.
if (is_max())
return std::numeric_limits<CFAbsoluteTime>::infinity();
return (static_cast<CFAbsoluteTime>(us_ - kTimeTToMicrosecondsOffset) /
kMicrosecondsPerSecond) -
kCFAbsoluteTimeIntervalSince1970;
return is_max() ? std::numeric_limits<CFAbsoluteTime>::infinity()
: (CFAbsoluteTime{(*this - UnixEpoch()).InSecondsF()} -
kCFAbsoluteTimeIntervalSince1970);
}
// TimeDelta ------------------------------------------------------------------
......
......@@ -1385,8 +1385,8 @@ TEST(TimeDelta, FromAndIn) {
TimeDelta::FromMillisecondsD(2.5) == TimeDelta::FromMicroseconds(2500),
"");
EXPECT_EQ(TimeDelta::FromDays(13).InDays(), 13);
EXPECT_EQ(TimeDelta::FromHours(13).InHours(), 13);
EXPECT_EQ(TimeDelta::FromMinutes(13).InMinutes(), 13);
static_assert(TimeDelta::FromHours(13).InHours() == 13, "");
static_assert(TimeDelta::FromMinutes(13).InMinutes() == 13, "");
EXPECT_EQ(TimeDelta::FromSeconds(13).InSeconds(), 13);
EXPECT_EQ(TimeDelta::FromSeconds(13).InSecondsF(), 13.0);
EXPECT_EQ(TimeDelta::FromMilliseconds(13).InMilliseconds(), 13);
......@@ -1395,20 +1395,21 @@ TEST(TimeDelta, FromAndIn) {
EXPECT_EQ(TimeDelta::FromSecondsD(13.1).InSecondsF(), 13.1);
EXPECT_EQ(TimeDelta::FromMillisecondsD(13.3).InMilliseconds(), 13);
EXPECT_EQ(TimeDelta::FromMillisecondsD(13.3).InMillisecondsF(), 13.3);
EXPECT_EQ(TimeDelta::FromMicroseconds(13).InMicroseconds(), 13);
EXPECT_EQ(TimeDelta::FromMicrosecondsD(13.3).InMicroseconds(), 13);
static_assert(TimeDelta::FromMicroseconds(13).InMicroseconds() == 13, "");
static_assert(TimeDelta::FromMicrosecondsD(13.3).InMicroseconds() == 13, "");
EXPECT_EQ(TimeDelta::FromMillisecondsD(3.45678).InMillisecondsF(), 3.456);
EXPECT_EQ(TimeDelta::FromNanoseconds(12345).InNanoseconds(), 12000);
EXPECT_EQ(TimeDelta::FromNanosecondsD(12345.678).InNanoseconds(), 12000);
static_assert(TimeDelta::FromNanoseconds(12345).InNanoseconds() == 12000, "");
static_assert(TimeDelta::FromNanosecondsD(12345.678).InNanoseconds() == 12000,
"");
}
TEST(TimeDelta, InRoundsTowardsZero) {
EXPECT_EQ(TimeDelta::FromHours(23).InDays(), 0);
EXPECT_EQ(TimeDelta::FromHours(-23).InDays(), 0);
EXPECT_EQ(TimeDelta::FromMinutes(59).InHours(), 0);
EXPECT_EQ(TimeDelta::FromMinutes(-59).InHours(), 0);
EXPECT_EQ(TimeDelta::FromSeconds(59).InMinutes(), 0);
EXPECT_EQ(TimeDelta::FromSeconds(-59).InMinutes(), 0);
static_assert(TimeDelta::FromMinutes(59).InHours() == 0, "");
static_assert(TimeDelta::FromMinutes(-59).InHours() == 0, "");
static_assert(TimeDelta::FromSeconds(59).InMinutes() == 0, "");
static_assert(TimeDelta::FromSeconds(-59).InMinutes() == 0, "");
EXPECT_EQ(TimeDelta::FromMilliseconds(999).InSeconds(), 0);
EXPECT_EQ(TimeDelta::FromMilliseconds(-999).InSeconds(), 0);
EXPECT_EQ(TimeDelta::FromMicroseconds(999).InMilliseconds(), 0);
......@@ -1602,8 +1603,8 @@ TEST(TimeDelta, MaxConversions) {
static_assert(kMax.ToInternalValue() == std::numeric_limits<int64_t>::max(),
"");
EXPECT_EQ(kMax.InDays(), std::numeric_limits<int>::max());
EXPECT_EQ(kMax.InHours(), std::numeric_limits<int>::max());
EXPECT_EQ(kMax.InMinutes(), std::numeric_limits<int>::max());
static_assert(kMax.InHours() == std::numeric_limits<int>::max(), "");
static_assert(kMax.InMinutes() == std::numeric_limits<int>::max(), "");
EXPECT_EQ(kMax.InSecondsF(), std::numeric_limits<double>::infinity());
EXPECT_EQ(kMax.InSeconds(), std::numeric_limits<int64_t>::max());
EXPECT_EQ(kMax.InMillisecondsF(), std::numeric_limits<double>::infinity());
......@@ -1693,8 +1694,8 @@ TEST(TimeDelta, MinConversions) {
constexpr TimeDelta kMin = TimeDelta::Min();
EXPECT_EQ(kMin.InDays(), std::numeric_limits<int>::min());
EXPECT_EQ(kMin.InHours(), std::numeric_limits<int>::min());
EXPECT_EQ(kMin.InMinutes(), std::numeric_limits<int>::min());
static_assert(kMin.InHours() == std::numeric_limits<int>::min(), "");
static_assert(kMin.InMinutes() == std::numeric_limits<int>::min(), "");
EXPECT_EQ(kMin.InSecondsF(), -std::numeric_limits<double>::infinity());
EXPECT_EQ(kMin.InSeconds(), std::numeric_limits<int64_t>::min());
EXPECT_EQ(kMin.InMillisecondsF(), -std::numeric_limits<double>::infinity());
......
......@@ -38,6 +38,8 @@
#include <mmsystem.h>
#include <stdint.h>
#include <atomic>
#include "base/atomicops.h"
#include "base/bit_cast.h"
#include "base/check_op.h"
......@@ -341,13 +343,8 @@ bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) {
success = !!SystemTimeToFileTime(&st, &ft);
}
if (!success) {
*time = Time(0);
return false;
}
*time = Time(FileTimeToMicroseconds(ft));
return true;
*time = Time(success ? FileTimeToMicroseconds(ft) : 0);
return success;
}
void Time::Explode(bool is_local, Exploded* exploded) const {
......@@ -378,7 +375,6 @@ void Time::Explode(bool is_local, Exploded* exploded) const {
}
if (!success) {
NOTREACHED() << "Unable to convert time, don't know why";
ZeroMemory(exploded, sizeof(*exploded));
return;
}
......@@ -515,15 +511,10 @@ TimeTicksNowFunction g_time_ticks_now_ignoring_override_function =
&InitialNowFunction;
int64_t g_qpc_ticks_per_second = 0;
// As of January 2015, use of <atomic> is forbidden in Chromium code. This is
// what std::atomic_thread_fence does on Windows on all Intel architectures when
// the memory_order argument is anything but std::memory_order_seq_cst:
#define ATOMIC_THREAD_FENCE(memory_order) _ReadWriteBarrier();
TimeDelta QPCValueToTimeDelta(LONGLONG qpc_value) {
// Ensure that the assignment to |g_qpc_ticks_per_second|, made in
// InitializeNowFunctionPointer(), has happened by this point.
ATOMIC_THREAD_FENCE(memory_order_acquire);
std::atomic_thread_fence(std::memory_order_acquire);
DCHECK_GT(g_qpc_ticks_per_second, 0);
......@@ -562,13 +553,11 @@ void InitializeNowFunctionPointer() {
//
// Otherwise, Now uses the high-resolution QPC clock. As of 21 August 2015,
// ~72% of users fall within this category.
TimeTicksNowFunction now_function;
CPU cpu;
if (ticks_per_sec.QuadPart <= 0 || !cpu.has_non_stop_time_stamp_counter()) {
now_function = &RolloverProtectedNow;
} else {
now_function = &QPCNow;
}
const TimeTicksNowFunction now_function =
(ticks_per_sec.QuadPart <= 0 || !cpu.has_non_stop_time_stamp_counter())
? &RolloverProtectedNow
: &QPCNow;
// Threading note 1: In an unlikely race condition, it's possible for two or
// more threads to enter InitializeNowFunctionPointer() in parallel. This is
......@@ -580,7 +569,7 @@ void InitializeNowFunctionPointer() {
// assignment to |g_qpc_ticks_per_second| happens before the function pointers
// are changed.
g_qpc_ticks_per_second = ticks_per_sec.QuadPart;
ATOMIC_THREAD_FENCE(memory_order_release);
std::atomic_thread_fence(std::memory_order_release);
// Also set g_time_ticks_now_function to avoid the additional indirection via
// TimeTicksNowIgnoringOverride() for future calls to TimeTicks::Now(). But
// g_time_ticks_now_function may have already be overridden.
......@@ -642,8 +631,8 @@ bool TimeTicks::IsConsistentAcrossProcesses() {
// static
TimeTicks::Clock TimeTicks::GetClock() {
return IsHighResolution() ?
Clock::WIN_QPC : Clock::WIN_ROLLOVER_PROTECTED_TIME_GET_TIME;
return IsHighResolution() ? Clock::WIN_QPC
: Clock::WIN_ROLLOVER_PROTECTED_TIME_GET_TIME;
}
// ThreadTicks ----------------------------------------------------------------
......@@ -670,23 +659,24 @@ ThreadTicks ThreadTicks::GetForThread(
::GetThreadTimes(thread_handle.platform_handle(), &creation_time, &exit_time,
&kernel_time, &user_time);
int64_t us = FileTimeToMicroseconds(user_time);
return ThreadTicks(us);
const int64_t us = FileTimeToMicroseconds(user_time);
#else
// Get the number of TSC ticks used by the current thread.
ULONG64 thread_cycle_time = 0;
::QueryThreadCycleTime(thread_handle.platform_handle(), &thread_cycle_time);
// Get the frequency of the TSC.
double tsc_ticks_per_second = TSCTicksPerSecond();
const double tsc_ticks_per_second = TSCTicksPerSecond();
if (tsc_ticks_per_second == 0)
return ThreadTicks();
// Return the CPU time of the current thread.
double thread_time_seconds = thread_cycle_time / tsc_ticks_per_second;
return ThreadTicks(
static_cast<int64_t>(thread_time_seconds * Time::kMicrosecondsPerSecond));
const double thread_time_seconds = thread_cycle_time / tsc_ticks_per_second;
const int64_t us =
static_cast<int64_t>(thread_time_seconds * Time::kMicrosecondsPerSecond);
#endif
return ThreadTicks(us);
}
// static
......@@ -717,7 +707,7 @@ double ThreadTicks::TSCTicksPerSecond() {
// Increase the thread priority to reduces the chances of having a context
// switch during a reading of the TSC and the performance counter.
int previous_priority = ::GetThreadPriority(::GetCurrentThread());
const int previous_priority = ::GetThreadPriority(::GetCurrentThread());
::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
// The first time that this function is called, make an initial reading of the
......@@ -728,8 +718,8 @@ double ThreadTicks::TSCTicksPerSecond() {
// Make a another reading of the TSC and the performance counter every time
// that this function is called.
uint64_t tsc_now = __rdtsc();
uint64_t perf_counter_now = QPCNowRaw();
const uint64_t tsc_now = __rdtsc();
const uint64_t perf_counter_now = QPCNowRaw();
// Reset the thread priority.
::SetThreadPriority(::GetCurrentThread(), previous_priority);
......@@ -746,17 +736,17 @@ double ThreadTicks::TSCTicksPerSecond() {
LARGE_INTEGER perf_counter_frequency = {};
::QueryPerformanceFrequency(&perf_counter_frequency);
DCHECK_GE(perf_counter_now, perf_counter_initial);
uint64_t perf_counter_ticks = perf_counter_now - perf_counter_initial;
double elapsed_time_seconds =
const uint64_t perf_counter_ticks = perf_counter_now - perf_counter_initial;
const double elapsed_time_seconds =
perf_counter_ticks / static_cast<double>(perf_counter_frequency.QuadPart);
static constexpr double kMinimumEvaluationPeriodSeconds = 0.05;
constexpr double kMinimumEvaluationPeriodSeconds = 0.05;
if (elapsed_time_seconds < kMinimumEvaluationPeriodSeconds)
return 0;
// Compute the frequency of the TSC.
DCHECK_GE(tsc_now, tsc_initial);
uint64_t tsc_ticks = tsc_now - tsc_initial;
const uint64_t tsc_ticks = tsc_now - tsc_initial;
tsc_ticks_per_second = tsc_ticks / elapsed_time_seconds;
return tsc_ticks_per_second;
......
......@@ -9,6 +9,7 @@
#include <stdint.h>
#include <windows.foundation.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
......@@ -151,23 +152,19 @@ TEST(TimeTicks, SubMillisecondTimers) {
if (!TimeTicks::IsHighResolution())
return;
const int kRetries = 1000;
bool saw_submillisecond_timer = false;
// Run kRetries attempts to see a sub-millisecond timer.
constexpr int kRetries = 1000;
for (int index = 0; index < kRetries; index++) {
TimeTicks last_time = TimeTicks::Now();
const TimeTicks start_time = TimeTicks::Now();
TimeDelta delta;
// Spin until the clock has detected a change.
do {
delta = TimeTicks::Now() - last_time;
} while (delta.InMicroseconds() == 0);
if (delta.InMicroseconds() < 1000) {
saw_submillisecond_timer = true;
break;
}
delta = TimeTicks::Now() - start_time;
} while (delta.is_zero());
if (!delta.InMilliseconds())
return;
}
EXPECT_TRUE(saw_submillisecond_timer);
ADD_FAILURE() << "Never saw a sub-millisecond timer.";
}
TEST(TimeTicks, TimeGetTimeCaps) {
......@@ -324,7 +321,7 @@ TEST(TimeTicks, FromQPCValue) {
ticks_per_second;
const TimeTicks converted_value = TimeTicks::FromQPCValue(ticks);
const double converted_microseconds_since_origin =
static_cast<double>((converted_value - TimeTicks()).InMicroseconds());
(converted_value - TimeTicks()).InMicrosecondsF();
// When we test with very large numbers we end up in a range where adjacent
// double values are far apart - 512.0 apart in one test failure. In that
// situation it makes no sense for our epsilon to be 1.0 - it should be
......@@ -338,9 +335,7 @@ TEST(TimeTicks, FromQPCValue) {
// slightly larger than 1.0, even when the converted value is perfect. This
// epsilon value was chosen because it is slightly larger than the error
// seen in a test failure caused by the double rounding.
const double min_epsilon = 1.002;
if (epsilon < min_epsilon)
epsilon = min_epsilon;
epsilon = std::max(epsilon, 1.002);
EXPECT_NEAR(expected_microseconds_since_origin,
converted_microseconds_since_origin, epsilon)
<< "ticks=" << ticks << ", to be converted via logic path: "
......
......@@ -31,12 +31,10 @@ const base::TimeDelta kSignificantlyAboveThresholdDelayMs =
class FakeTickClock : public base::TickClock {
public:
FakeTickClock() = default;
// The |dns_resolution_delay| fakes the duration of a DNS resolution.
explicit FakeTickClock(const base::TimeDelta& dns_resolution_delay)
: current_time_(base::TimeTicks::Now()),
dns_resolution_delay_(dns_resolution_delay) {}
explicit FakeTickClock(
const base::TimeDelta& dns_resolution_delay = base::TimeDelta())
: dns_resolution_delay_(dns_resolution_delay) {}
~FakeTickClock() override = default;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment