第三方框架改为仓内子集并完善构建忽略规则

完整 NIM_Duilib_Framework 仓库移至父目录,third_party 仅保留实际使用的 base、duilib、bin/resources 与许可证;.gitignore 覆盖 MSBuild 与打包产物。
This commit is contained in:
tongtong committed 2026-11-15 08:54:17 +08:00
1 parent 249e8548de
commit e1e26acc49
391 files changed
+342850

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
// Copyright (c) 2011, NetEase Inc. All rights reserved.
//
// Author: rl
// Date: 2011/6/9
//
// TimeDelta/Time/TimeTicks implementation
#include "base/time/time.h"
namespace nbase
{
// TimeDelta ------------------------------------------------------------------
int TimeDelta::ToDays() const
{
return static_cast<int>(delta_ / Time::kMicrosecondsPerDay);
}
int TimeDelta::ToHours() const
{
return static_cast<int>(delta_ / Time::kMicrosecondsPerHour);
}
int TimeDelta::ToMinutes() const
{
return static_cast<int>(delta_ / Time::kMicrosecondsPerMinute);
}
double TimeDelta::ToSecondsF() const
{
return static_cast<double>(delta_) / Time::kMicrosecondsPerSecond;
}
int64_t TimeDelta::ToSeconds() const
{
return delta_ / Time::kMicrosecondsPerSecond;
}
double TimeDelta::ToMillisecondsF() const
{
return static_cast<double>(delta_) / Time::kMicrosecondsPerMillisecond;
}
int64_t TimeDelta::ToMilliseconds() const
{
return delta_ / Time::kMicrosecondsPerMillisecond;
}
int64_t TimeDelta::ToMillisecondsRoundedUp() const
{
return (delta_ + Time::kMicrosecondsPerMillisecond - 1) /
Time::kMicrosecondsPerMillisecond;
}
int64_t TimeDelta::ToMicroseconds() const
{
return delta_;
}
// Time::TimeStruct -------------------------------------------------------------
inline bool is_in_range(int value, int lo, int hi)
{
return lo <= value && value <= hi;
}
bool Time::TimeStruct::IsValidValues() const
{
return is_in_range(month_, 1, 12) &&
is_in_range(day_of_week_, 0, 6) &&
is_in_range(day_of_month_, 1, 31) &&
is_in_range(hour_, 0, 23) &&
is_in_range(minute_, 0, 59) &&
is_in_range(second_, 0, 60) &&
is_in_range(millisecond_, 0, 999);
}
// Time -----------------------------------------------------------------------
Time::Time(bool is_local, TimeStruct &ts)
{
us_ = FromTimeStruct(is_local, ts).us_;
}
Time::Time(bool is_local, int year, int month, int day,
int hour, int minute, int second, int millisecond/* = 0*/)
{
Time::TimeStruct ts;
ts.year_ = year;
ts.month_ = month;
ts.day_of_month_ = day;
ts.day_of_week_ = 0;
ts.hour_ = hour;
ts.minute_ = minute;
ts.second_ = second;
ts.millisecond_ = millisecond;
us_ = FromTimeStruct(is_local, ts).us_;
}
// static
Time Time::FromTimeT(time_t tt)
{
if (tt == 0)
return Time(); // Preserve 0 so we can tell it doesn't exist.
return Time((tt * kMicrosecondsPerSecond) + kTimeTToMicrosecondsOffset);
}
time_t Time::ToTimeT() const
{
if (us_ == 0)
return 0; // Preserve 0 so we can tell it doesn't exist.
return (us_ - kTimeTToMicrosecondsOffset) / kMicrosecondsPerSecond;
}
} // namespace nbase
+478
View File
@@ -0,0 +1,478 @@
// Time represents an absolute point in time, internally represented as
// microseconds (s/1,000,000) since a platform-dependent epoch. Each
// platform's epoch, along with other system-dependent clock interface
// routines, is defined in time_PLATFORM.cc.
//
// TimeDelta represents a duration of time, internally represented in
// microseconds.
//
// TimeTicks represents an abstract time that is always incrementing for use
// in measuring time durations. It is internally represented in microseconds.
// It can not be converted to a human-readable time, but is guaranteed not to
// decrease (if the user changes the computer clock, Time::Now() may actually
// decrease or jump).
#ifndef BASE_TIME_TIME_H_
#define BASE_TIME_TIME_H_
#include <time.h>
#include "base/base_types.h"
#include "base/base_export.h"
#if defined(OS_WIN)
# include <windows.h>
#else
# include <sys/time.h>
#endif // OS_WIN
namespace nbase
{
class Time;
class TimeTicks;
class BASE_EXPORT TimeDelta
{
public:
TimeDelta() : delta_(0) {}
// Converts units of time to TimeDeltas.
static TimeDelta FromDays(int64_t days);
static TimeDelta FromHours(int64_t hours);
static TimeDelta FromMinutes(int64_t minutes);
static TimeDelta FromSeconds(int64_t secs);
static TimeDelta FromMilliseconds(int64_t ms);
static TimeDelta FromMicroseconds(int64_t us);
// Returns the internal numeric value of the TimeDelta object.
int64_t ToInternalValue() const
{
return delta_;
}
#if defined(OS_POSIX)
struct timespec ToTimeSpec() const;
#endif
// Returns the time delta in some unit. The F versions return a floating
// point value, the "regular" versions return a rounded-down value.
int ToDays() const;
int ToHours() const;
int ToMinutes() const;
double ToSecondsF() const;
int64_t ToSeconds() const;
double ToMillisecondsF() const;
int64_t ToMilliseconds() const;
int64_t ToMillisecondsRoundedUp() const;
int64_t ToMicroseconds() const;
TimeDelta& operator=(TimeDelta other)
{
delta_ = other.delta_;
return *this;
}
// Computations with other deltas.
TimeDelta operator+(TimeDelta other) const
{
return TimeDelta(delta_ + other.delta_);
}
TimeDelta operator-(TimeDelta other) const
{
return TimeDelta(delta_ - other.delta_);
}
TimeDelta& operator+=(TimeDelta other)
{
delta_ += other.delta_;
return *this;
}
TimeDelta& operator-=(TimeDelta other)
{
delta_ -= other.delta_;
return *this;
}
TimeDelta operator-() const
{
return TimeDelta(-delta_);
}
// Computations with ints, note that we only allow multiplicative operations
// with ints, and additive operations with other deltas.
TimeDelta operator*(int64_t a) const
{
return TimeDelta(delta_ * a);
}
TimeDelta operator/(int64_t a) const
{
return TimeDelta(delta_ / a);
}
TimeDelta& operator*=(int64_t a)
{
delta_ *= a;
return *this;
}
TimeDelta& operator/=(int64_t a)
{
delta_ /= a;
return *this;
}
int64_t operator/(TimeDelta a) const
{
return delta_ / a.delta_;
}
// Defined below because it depends on the definition of the other classes.
Time operator+(Time t) const;
TimeTicks operator+(TimeTicks t) const;
// Comparison operators.
bool operator==(TimeDelta other) const
{
return delta_ == other.delta_;
}
bool operator!=(TimeDelta other) const
{
return delta_ != other.delta_;
}
bool operator<(TimeDelta other) const
{
return delta_ < other.delta_;
}
bool operator<=(TimeDelta other) const
{
return delta_ <= other.delta_;
}
bool operator>(TimeDelta other) const
{
return delta_ > other.delta_;
}
bool operator>=(TimeDelta other) const
{
return delta_ >= other.delta_;
}
private:
friend class Time;
friend class TimeTicks;
friend TimeDelta operator*(int64_t a, TimeDelta td);
// Constructs a delta given the duration in microseconds.
explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {}
// Delta in microseconds.
int64_t delta_;
};
inline TimeDelta operator*(int64_t a, TimeDelta td)
{
return TimeDelta(a * td.delta_);
}
// Time -----------------------------------------------------------------------
// Represents a wall clock time.
class BASE_EXPORT Time
{
public:
static const int64_t kMillisecondsPerSecond = 1000;
static const int64_t kMicrosecondsPerMillisecond = 1000;
static const int64_t kMicrosecondsPerSecond = kMicrosecondsPerMillisecond *
kMillisecondsPerSecond;
static const int64_t kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
static const int64_t kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
static const int64_t kMicrosecondsPerDay = kMicrosecondsPerHour * 24;
static const int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
static const int64_t kNanosecondsPerMicrosecond = 1000;
static const int64_t kNanosecondsPerSecond = kNanosecondsPerMicrosecond *
kMicrosecondsPerSecond;
#if !defined(OS_WIN)
// On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
// the Posix delta of 1970. This is used for migrating between the old
// 1970-based epochs to the new 1601-based ones. It should be removed from
// this global header and put in the platform-specific ones when we remove the
// migration code.
static const int64_t kWindowsEpochDeltaMicroseconds;
#endif
// Represents an exploded time that can be formatted nicely. This is kind of
// like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
// additions and changes to prevent errors.
struct BASE_EXPORT TimeStruct
{
int year_; // Four digit year "2011"
int month_; // 1-based month (values 1 = January, etc.)
int day_of_week_; // 0-based day of week (0 = Sunday, etc.)
int day_of_month_; // 1-based day of month (1-31)
int hour_; // Hour within the current day (0-23)
int minute_; // Minute within the current hour (0-59)
int second_; // Second within the current minute (0-59).
int millisecond_; // Milliseconds within the current second (0-999)
explicit TimeStruct()
: year_(0), month_(0), day_of_week_(0), day_of_month_(0), hour_(0),
minute_(0), second_(0), millisecond_(0)
{}
bool IsValidValues() const;
int year() { return year_; }
int month() { return month_; }
int day_of_week() { return day_of_week_; }
int day_of_month() { return day_of_month_; }
int hour() { return hour_; }
int minute() { return minute_; }
int second() { return second_; }
int millisecond() { return millisecond_; }
};
public:
explicit Time() : us_(0) {}
explicit Time(int64_t us) : us_(us) {}
explicit Time(bool is_local, TimeStruct &ts);
explicit Time(bool is_local,
int year, int month, int day, int hour, int minute, int second, int millisecond = 0);
bool is_null() const { return us_ == 0; }
int64_t ToInternalValue() const { return us_; }
// Returns the current time.
static Time Now();
// Converts to/from TimeStruct in UTC and a Time class.
static Time FromTimeStruct(bool is_local, TimeStruct &ts);
TimeStruct ToTimeStruct(bool is_local);
// Converts to/from time_t in UTC and a Time class.
static Time FromTimeT(time_t tt);
time_t ToTimeT() const;
#if defined(OS_WIN)
// Converts to/from FILETIME.
static Time FromFileTime(FILETIME ft);
FILETIME ToFileTime() const;
#endif // OS_WIN
Time& operator=(Time other)
{
us_ = other.us_;
return *this;
}
// Compute the difference between two times.
TimeDelta operator-(Time other) const
{
return TimeDelta(us_ - other.us_);
}
// Modify by some time delta.
Time& operator+=(TimeDelta delta)
{
us_ += delta.delta_;
return *this;
}
Time& operator-=(TimeDelta delta)
{
us_ -= delta.delta_;
return *this;
}
// Return a new time modified by some delta.
Time operator+(TimeDelta delta) const
{
return Time(us_ + delta.delta_);
}
Time operator-(TimeDelta delta) const
{
return Time(us_ - delta.delta_);
}
// Comparison operators
bool operator==(Time other) const
{
return us_ == other.us_;
}
bool operator!=(Time other) const
{
return us_ != other.us_;
}
bool operator<(Time other) const
{
return us_ < other.us_;
}
bool operator<=(Time other) const
{
return us_ <= other.us_;
}
bool operator>(Time other) const
{
return us_ > other.us_;
}
bool operator>=(Time other) const
{
return us_ >= other.us_;
}
private:
friend class TimeDelta;
// The representation of Jan 1, 1970 UTC in microseconds since the
// platform-dependent epoch.
static const int64_t kTimeTToMicrosecondsOffset;
// NTime in microseconds in UTC.
int64_t us_;
};
// Inline the TimeDelta factory methods, for fast TimeDelta construction.
// static
inline TimeDelta TimeDelta::FromDays(int64_t days)
{
return TimeDelta(days * Time::kMicrosecondsPerDay);
}
// static
inline TimeDelta TimeDelta::FromHours(int64_t hours)
{
return TimeDelta(hours * Time::kMicrosecondsPerHour);
}
// static
inline TimeDelta TimeDelta::FromMinutes(int64_t minutes)
{
return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
}
// static
inline TimeDelta TimeDelta::FromSeconds(int64_t secs)
{
return TimeDelta(secs * Time::kMicrosecondsPerSecond);
}
// static
inline TimeDelta TimeDelta::FromMilliseconds(int64_t ms)
{
return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
}
// static
inline TimeDelta TimeDelta::FromMicroseconds(int64_t us)
{
return TimeDelta(us);
}
inline Time TimeDelta::operator+(Time t) const
{
return Time(t.us_ + delta_);
}
// TimeTicks ------------------------------------------------------------------
class BASE_EXPORT TimeTicks
{
public:
TimeTicks() : ticks_(0) {}
explicit TimeTicks(int64_t ticks) : ticks_(ticks) {}
// Platform-dependent tick count representing "right now."
// The resolution of this clock is ~1-15ms. Resolution varies depending
// on hardware/operating system configuration.
static TimeTicks Now();
// Returns a platform-dependent high-resolution tick count. Implementation
// is hardware dependent and may or may not return sub-millisecond
// resolution. THIS CALL IS GENERALLY MUCH MORE EXPENSIVE THAN Now() AND
// SHOULD ONLY BE USED WHEN IT IS REALLY NEEDED.
static TimeTicks HighResNow();
// Returns true if this object has not been initialized.
bool is_null() const
{
return ticks_ == 0;
}
// Returns the internal numeric value of the TimeTicks object.
int64_t ToInternalValue() const
{
return ticks_;
}
TimeTicks& operator=(TimeTicks other)
{
ticks_ = other.ticks_;
return *this;
}
// Compute the difference between two times.
TimeDelta operator-(TimeTicks other) const
{
return TimeDelta(ticks_ - other.ticks_);
}
// Modify by some time delta.
TimeTicks& operator+=(TimeDelta delta)
{
ticks_ += delta.delta_;
return *this;
}
TimeTicks& operator-=(TimeDelta delta)
{
ticks_ -= delta.delta_;
return *this;
}
// Return a new TimeTicks modified by some delta.
TimeTicks operator+(TimeDelta delta) const
{
return TimeTicks(ticks_ + delta.delta_);
}
TimeTicks operator-(TimeDelta delta) const
{
return TimeTicks(ticks_ - delta.delta_);
}
// Comparison operators
bool operator==(TimeTicks other) const
{
return ticks_ == other.ticks_;
}
bool operator!=(TimeTicks other) const
{
return ticks_ != other.ticks_;
}
bool operator<(TimeTicks other) const
{
return ticks_ < other.ticks_;
}
bool operator<=(TimeTicks other) const
{
return ticks_ <= other.ticks_;
}
bool operator>(TimeTicks other) const
{
return ticks_ > other.ticks_;
}
bool operator>=(TimeTicks other) const
{
return ticks_ >= other.ticks_;
}
protected:
friend class TimeDelta;
// Tick count in microseconds.
int64_t ticks_;
};
inline TimeTicks TimeDelta::operator+(TimeTicks t) const
{
return TimeTicks(t.ticks_ + delta_);
}
} // namespace nbase
#endif // BASE_TIME_TIME_H_
@@ -0,0 +1,259 @@
// Copyright (c) 2011, NetEase Inc. All rights reserved.
//
// Author: rl
// Date: 2011/6/9
//
// TimeDelta/Time/TimeTicks implementation on posix platform
#include "base/time/time.h"
#if defined(OS_POSIX)
#include <sys/time.h>
#include <time.h>
#include <limits>
#if defined(OS_MACOSX) || defined(OS_IOS)
#include <mach/mach_time.h>
#endif
namespace nbase
{
// TimeDelta -----------------------------------------------------------------------
struct timespec TimeDelta::ToTimeSpec() const
{
int64_t microseconds = ToMicroseconds();
time_t seconds = 0;
if (microseconds >= Time::kMicrosecondsPerSecond)
{
seconds = ToSeconds();
microseconds -= seconds * Time::kMicrosecondsPerSecond;
}
struct timespec result = {seconds,
microseconds * Time::kNanosecondsPerMicrosecond};
return result;
}
// Time -----------------------------------------------------------------------
// Windows uses a Gregorian epoch of 1601. We need to match this internally
// so that our time representations match across all platforms. See bug 14734.
// irb(main):010:0> Time.at(0).getutc()
// => Thu Jan 01 00:00:00 UTC 1970
// irb(main):011:0> Time.at(-11644473600).getutc()
// => Mon Jan 01 00:00:00 UTC 1601
static const int64_t kWindowsEpochDeltaSeconds = GG_INT64_C(11644473600);
static const int64_t kWindowsEpochDeltaMilliseconds =
kWindowsEpochDeltaSeconds * Time::kMillisecondsPerSecond;
// static
const int64_t Time::kWindowsEpochDeltaMicroseconds =
kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond;
// Some functions in time.cc use time_t directly, so we provide an offset
// to convert from time_t (Unix epoch) and internal (Windows epoch).
// static
const int64_t Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds;
// static
Time Time::Now()
{
struct timeval tv;
struct timezone tz = { 0, 0 }; // UTC
if (gettimeofday(&tv, &tz) != 0)
{
}
// Combine seconds and microseconds in a 64-bit field containing microseconds
// since the epoch. That's enough for nearly 600 centuries. Adjust from
// Unix (1970) to Windows (1601) epoch.
return Time((tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec) +
kWindowsEpochDeltaMicroseconds);
}
Time::TimeStruct Time::ToTimeStruct(bool is_local)
{
TimeStruct ts;
// Time stores times with microsecond resolution, but Exploded only carries
// millisecond resolution, so begin by being lossy. Adjust from Windows
// epoch (1601) to Unix epoch (1970);
int64_t milliseconds = (us_ - kWindowsEpochDeltaMicroseconds) /
kMicrosecondsPerMillisecond;
time_t seconds = milliseconds / kMillisecondsPerSecond;
struct tm timestruct;
if (is_local)
localtime_r(&seconds, &timestruct);
else
gmtime_r(&seconds, &timestruct);
ts.year_ = timestruct.tm_year + 1900;
ts.month_ = timestruct.tm_mon + 1;
ts.day_of_week_ = timestruct.tm_wday;
ts.day_of_month_ = timestruct.tm_mday;
ts.hour_ = timestruct.tm_hour;
ts.minute_ = timestruct.tm_min;
ts.second_ = timestruct.tm_sec;
ts.millisecond_ = milliseconds % kMillisecondsPerSecond;
return ts;
}
// static
Time Time::FromTimeStruct(bool is_local, TimeStruct &ts)
{
struct tm timestruct;
timestruct.tm_sec = ts.second();
timestruct.tm_min = ts.minute();
timestruct.tm_hour = ts.hour();
timestruct.tm_mday = ts.day_of_month();
timestruct.tm_mon = ts.month() - 1;
timestruct.tm_year = ts.year() - 1900;
timestruct.tm_wday = ts.day_of_week(); // mktime/timegm ignore this
timestruct.tm_yday = 0; // mktime/timegm ignore this
timestruct.tm_isdst = -1; // attempt to figure it out
timestruct.tm_gmtoff = 0; // not a POSIX field, so mktime/timegm ignore
timestruct.tm_zone = NULL; // not a POSIX field, so mktime/timegm ignore
time_t seconds;
if (is_local)
seconds = mktime(&timestruct);
else
seconds = timegm(&timestruct);
int64_t milliseconds;
// Handle overflow. Clamping the range to what mktime and timegm might
// return is the best that can be done here. It's not ideal, but it's better
// than failing here or ignoring the overflow case and treating each time
// overflow as one second prior to the epoch.
if (seconds == -1 &&
(ts.year() < 1969 || ts.year() > 1970))
{
// If exploded.year is 1969 or 1970, take -1 as correct, with the
// time indicating 1 second prior to the epoch. (1970 is allowed to handle
// time zone and DST offsets.) Otherwise, return the most future or past
// time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC.
//
// The minimum and maximum representible times that mktime and timegm could
// return are used here instead of values outside that range to allow for
// proper round-tripping between exploded and counter-type time
// representations in the presence of possible truncation to time_t by
// division and use with other functions that accept time_t.
//
// When representing the most distant time in the future, add in an extra
// 999ms to avoid the time being less than any other possible value that
// this function can return.
if (ts.year() < 1969)
{
milliseconds = std::numeric_limits<time_t>::min() *
kMillisecondsPerSecond;
}
else
{
milliseconds = (std::numeric_limits<time_t>::max() *
kMillisecondsPerSecond) +
kMillisecondsPerSecond - 1;
}
}
else
{
milliseconds = seconds * kMillisecondsPerSecond + ts.millisecond();
}
// Adjust from Unix (1970) to Windows (1601) epoch.
return Time((milliseconds * kMicrosecondsPerMillisecond) +
kWindowsEpochDeltaMicroseconds);
}
// TimeTicks ------------------------------------------------------------------
#if defined(OS_MACOSX) || defined(OS_IOS)
// static
TimeTicks TimeTicks::Now()
{
uint64_t absolute_micro;
static mach_timebase_info_data_t timebase_info;
if (timebase_info.denom == 0)
{
// Zero-initialization of statics guarantees that denom will be 0 before
// calling mach_timebase_info. mach_timebase_info will never set denom to
// 0 as that would be invalid, so the zero-check can be used to determine
// whether mach_timebase_info has already been called. This is
// recommended by Apple's QA1398.
mach_timebase_info(&timebase_info);
}
// mach_absolute_time is it when it comes to ticks on the Mac. Other calls
// with less precision (such as TickCount) just call through to
// mach_absolute_time.
// timebase_info converts absolute time tick units into nanoseconds. Convert
// to microseconds up front to stave off overflows.
absolute_micro = mach_absolute_time() / Time::kNanosecondsPerMicrosecond *
timebase_info.numer / timebase_info.denom;
// Don't bother with the rollover handling that the Windows version does.
// With numer and denom = 1 (the expected case), the 64-bit absolute time
// reported in nanoseconds is enough to last nearly 585 years.
return TimeTicks(absolute_micro);
}
#elif (defined(OS_POSIX) && \
defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0) || \
defined(OS_FREEBSD)
// static
TimeTicks TimeTicks::Now()
{
uint64_t absolute_micro;
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
{
return TimeTicks();
}
absolute_micro =
(static_cast<int64>(ts.tv_sec) * Time::kMicrosecondsPerSecond) +
(static_cast<int64>(ts.tv_nsec) / Time::kNanosecondsPerMicrosecond);
return TimeTicks(absolute_micro);
}
#else
// static
TimeTicks TimeTicks::Now()
{
uint64_t absolute_micro;
struct timeval tv;
struct timezone tz = { 0, 0 }; // UTC
if (gettimeofday(&tv, &tz) != 0)
{
return TimeTicks();
}
absolute_micro =
(static_cast<int64_t>(tv.tv_sec) * Time::kMicrosecondsPerSecond) +
(static_cast<int64_t>(tv.tv_usec));
return TimeTicks(absolute_micro);
}
#endif
// static
TimeTicks TimeTicks::HighResNow()
{
return TimeTicks::Now();
}
} // namespace nbase
#endif // OS_POSIX
+315
View File
@@ -0,0 +1,315 @@
// Copyright (c) 2011, NetEase Inc. All rights reserved.
//
// Author: rl
// Date: 2011/6/9
//
// TimeDelta/Time/TimeTicks implementation on windows platform
#include "base/base_config.h"
#if defined(OS_WIN)
#include "base/base_export.h"
#include "base/hardware/cpu.h"
#include "base/synchronization/lock.h"
#include "base/time/time.h"
#if defined(COMPILER_MSVC)
#pragma comment(lib, "winmm.lib")
#endif
#include <stdlib.h> /* for abs(int64_t) in GCC */
#include <mmsystem.h>
namespace nbase
{
namespace
{
// From MSDN, FILETIME "Contains a 64-bit value representing the number of
// 100-nanosecond intervals since January 1, 1601 (UTC)."
int64_t FileTimeToMicroseconds(const FILETIME& ft)
{
// Need to bit_cast to fix alignment, then divide by 10 to convert
// 100-nanoseconds to milliseconds. This only works on little-endian
// machines.
return bit_cast<int64_t, FILETIME>(ft) / 10;
}
void MicrosecondsToFileTime(int64_t us, FILETIME* ft)
{
if (us < 0)
return;
// Multiply by 10 to convert milliseconds to 100-nanoseconds. Bit_cast will
// handle alignment problems. This only works on little-endian machines.
*ft = bit_cast<FILETIME, int64_t>(us * 10);
}
int64_t CurrentWallclockMicroseconds()
{
FILETIME ft;
::GetSystemTimeAsFileTime(&ft);
return FileTimeToMicroseconds(ft);
}
} // namespace
// NTime -----------------------------------------------------------------------
// The internal representation of NTime uses FILETIME, whose epoch is 1601-01-01
// 00:00:00 UTC. ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the
// number of leap year days between 1601 and 1970: (1970-1601)/4 excluding
// 1700, 1800, and 1900.
// static
const int64_t Time::kTimeTToMicrosecondsOffset = GG_INT64_C(11644473600000000);
// static
Time Time::Now()
{
int64_t us = CurrentWallclockMicroseconds();
return Time(us);
}
// static
Time Time::FromTimeStruct(bool is_local, TimeStruct &ts)
{
// Create the system struct representing our exploded time. It will either be
// in local time or UTC.
SYSTEMTIME st;
st.wYear = (WORD)ts.year();
st.wMonth = (WORD)ts.month();
st.wDayOfWeek = (WORD)ts.day_of_week();
st.wDay = (WORD)ts.day_of_month();
st.wHour = (WORD)ts.hour();
st.wMinute = (WORD)ts.minute();
st.wSecond = (WORD)ts.second();
st.wMilliseconds = (WORD)ts.millisecond();
// Convert to FILETIME.
FILETIME ft;
if (!SystemTimeToFileTime(&st, &ft))
{
return Time(0);
}
// Ensure that it's in UTC.
if (is_local)
{
FILETIME utc_ft;
LocalFileTimeToFileTime(&ft, &utc_ft);
return Time(FileTimeToMicroseconds(utc_ft));
}
return Time(FileTimeToMicroseconds(ft));
}
Time::TimeStruct Time::ToTimeStruct(bool is_local)
{
TimeStruct ts;
// FILETIME in UTC.
FILETIME utc_ft;
MicrosecondsToFileTime(us_, &utc_ft);
// FILETIME in local time if necessary.
BOOL success = TRUE;
FILETIME ft;
if (is_local)
success = FileTimeToLocalFileTime(&utc_ft, &ft);
else
ft = utc_ft;
// FILETIME in SYSTEMTIME (exploded).
SYSTEMTIME st;
if (!success || !FileTimeToSystemTime(&ft, &st))
{
return ts;
}
ts.year_ = st.wYear;
ts.month_ = st.wMonth;
ts.day_of_week_ = st.wDayOfWeek;
ts.day_of_month_ = st.wDay;
ts.hour_ = st.wHour;
ts.minute_ = st.wMinute;
ts.second_ = st.wSecond;
ts.millisecond_ = st.wMilliseconds;
return ts;
}
// static
Time Time::FromFileTime(FILETIME ft)
{
return Time(FileTimeToMicroseconds(ft));
}
FILETIME Time::ToFileTime() const
{
FILETIME utc_ft;
MicrosecondsToFileTime(us_, &utc_ft);
return utc_ft;
}
// TimeTicks ------------------------------------------------------------------
namespace
{
// Accumulation of time lost due to rollover (in milliseconds).
int64_t rollover_ms = 0;
// The last timeGetTime value we saw, to detect rollover.
DWORD last_seen_now = 0;
// Lock protecting rollover_ms and last_seen_now.
// Note: this is a global object, and we usually avoid these. However, the time
// code is low-level, and we don't want to use Singletons here (it would be too
// easy to use a Singleton without even knowing it, and that may lead to many
// gotchas). Its impact on startup time should be negligible due to low-level
// nature of time code.
nbase::NLock rollover_lock;
// We use timeGetTime() to implement TimeTicks::Now(). This can be problematic
// because it returns the number of milliseconds since Windows has started,
// which will roll over the 32-bit value every ~49 days. We try to track
// rollover ourselves, which works if TimeTicks::Now() is called at least every
// 49 days.
TimeDelta RolloverProtectedNow()
{
nbase::NAutoLock locked(&rollover_lock);
// We should hold the lock while calling tick_function to make sure that
// we keep last_seen_now stay correctly in sync.
DWORD now = timeGetTime();
if (now < last_seen_now)
rollover_ms += GG_LONGLONG(0x100000000); // ~49.7 days.
last_seen_now = now;
return TimeDelta::FromMilliseconds(now + rollover_ms);
}
// Overview of time counters:
// (1) CPU cycle counter. (Retrieved via RDTSC)
// The CPU counter provides the highest resolution time stamp and is the least
// expensive to retrieve. However, the CPU counter is unreliable and should not
// be used in production. Its biggest issue is that it is per processor and it
// is not synchronized between processors. Also, on some computers, the counters
// will change frequency due to thermal and power changes, and stop in some
// states.
//
// (2) QueryPerformanceCounter (QPC). The QPC counter provides a high-
// resolution (100 nanoseconds) time stamp but is comparatively more expensive
// to retrieve. What QueryPerformanceCounter actually does is up to the HAL.
// (with some help from ACPI).
// According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx
// in the worst case, it gets the counter from the rollover interrupt on the
// programmable interrupt timer. In best cases, the HAL may conclude that the
// RDTSC counter runs at a constant frequency, then it uses that instead. On
// multiprocessor machines, it will try to verify the values returned from
// RDTSC on each processor are consistent with each other, and apply a handful
// of workarounds for known buggy hardware. In other words, QPC is supposed to
// give consistent result on a multiprocessor computer, but it is unreliable in
// reality due to bugs in BIOS or HAL on some, especially old computers.
// With recent updates on HAL and newer BIOS, QPC is getting more reliable but
// it should be used with caution.
//
// (3) System time. The system time provides a low-resolution (typically 10ms
// to 55 milliseconds) time stamp but is comparatively less expensive to
// retrieve and more reliable.
class HighResNowSingleton
{
public:
static HighResNowSingleton* GetInstance()
{
static HighResNowSingleton instance;
return &instance;
}
bool IsUsingHighResClock()
{
return ticks_per_microsecond_ != 0.0;
}
void DisableHighResClock()
{
ticks_per_microsecond_ = 0.0;
}
TimeDelta Now()
{
if (IsUsingHighResClock())
return TimeDelta::FromMicroseconds(UnreliableNow());
// Just fallback to the slower clock.
return RolloverProtectedNow();
}
int64_t GetQPCDriftMicroseconds()
{
if (!IsUsingHighResClock())
return 0;
return abs((UnreliableNow() - ReliableNow()) - skew_);
}
private:
HighResNowSingleton()
: ticks_per_microsecond_(0.0), skew_(0)
{
InitializeClock();
// On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is
// unreliable. Fallback to low-res clock.
nbase::CPU cpu;
if (cpu.vendor_name() == "AuthenticAMD" && cpu.family() == 15)
DisableHighResClock();
}
// Synchronize the QPC clock with GetSystemTimeAsFileTime.
void InitializeClock()
{
LARGE_INTEGER ticks_per_sec = {{0}};
if (!QueryPerformanceFrequency(&ticks_per_sec))
return; // Broken, we don't guarantee this function works.
ticks_per_microsecond_ = static_cast<float>(ticks_per_sec.QuadPart) /
static_cast<float>(Time::kMicrosecondsPerSecond);
skew_ = UnreliableNow() - ReliableNow();
}
// Get the number of microseconds since boot in an unreliable fashion.
int64_t UnreliableNow()
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return static_cast<int64_t>(now.QuadPart / ticks_per_microsecond_);
}
// Get the number of microseconds since boot in a reliable fashion.
int64_t ReliableNow()
{
return RolloverProtectedNow().ToMicroseconds();
}
// Cached clock frequency -> microseconds. This assumes that the clock
// frequency is faster than one microsecond (which is 1MHz, should be OK).
float ticks_per_microsecond_; // 0 indicates QPF failed and we're broken.
int64_t skew_; // Skew between lo-res and hi-res clocks (for debugging).
};
} // namespace
// static
TimeTicks TimeTicks::Now()
{
return TimeTicks() + RolloverProtectedNow();
}
// static
TimeTicks TimeTicks::HighResNow()
{
return TimeTicks() + HighResNowSingleton::GetInstance()->Now();
}
} // namespace nbase
#endif // OS_WIN