Codebase list mozc / 26d5e5b
Move clock related functions to Clock in clock.cc. This CL factors out clock module from base:util to sort out dependencies. BUG= TEST=unittest REF_BUG=19010851 REF_CL=84935258 Noriyuki Takahashi authored 8 years ago Yohei Yukawa committed 8 years ago
38 changed file(s) with 563 addition(s) and 398 deletion(s). Raw diff Collapse all Expand all
9999 'sources': [
100100 '<(gen_out_dir)/character_set.h',
101101 '<(gen_out_dir)/version_def.h',
102 'clock.cc',
102103 'file_stream.cc',
103104 'file_util.cc',
104105 'flags.cc',
198198 },
199199 },
200200 {
201 'target_name': 'clock_test',
202 'type': 'executable',
203 'sources': [
204 'clock_test.cc',
205 ],
206 'dependencies': [
207 '../testing/testing.gyp:gtest_main',
208 'base.gyp:base',
209 ],
210 'variables': {
211 'test_size': 'small',
212 },
213 },
214 {
201215 'target_name': 'encoding_util_test',
202216 'type': 'executable',
203217 'sources': [
375389 'base_core_test',
376390 'base_init_test',
377391 'base_test',
392 'clock_test',
378393 'config_file_stream_test',
379394 'encoding_util_test',
380395 'encryptor_test',
0 // Copyright 2010-2015, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 #include "base/clock.h"
30
31 #ifdef OS_WIN
32 #include <Windows.h>
33 #include <time.h>
34 #else // OS_WIN
35 #ifdef OS_MACOSX
36 #include <mach/mach_time.h>
37 #elif defined(__native_client__) // OS_MACOSX
38 #include <irt.h>
39 #endif // OS_MACOSX or __native_client__
40 #include <sys/time.h>
41 #endif // OS_WIN
42
43 #include "base/singleton.h"
44
45 namespace mozc {
46 namespace {
47
48 class ClockImpl : public ClockInterface {
49 public:
50 #ifndef __native_client__
51 ClockImpl() {}
52 #else // __native_client__
53 ClockImpl() : timezone_offset_sec_(0) {}
54 #endif // __native_client__
55
56 virtual ~ClockImpl() {}
57
58 virtual void GetTimeOfDay(uint64 *sec, uint32 *usec) {
59 #ifdef OS_WIN
60 FILETIME file_time;
61 GetSystemTimeAsFileTime(&file_time);
62 ULARGE_INTEGER time_value;
63 time_value.HighPart = file_time.dwHighDateTime;
64 time_value.LowPart = file_time.dwLowDateTime;
65 // Convert into microseconds
66 time_value.QuadPart /= 10;
67 // kDeltaEpochInMicroSecs is difference between January 1, 1970 and
68 // January 1, 1601 in microsecond.
69 // This number is calculated as follows.
70 // ((1970 - 1601) * 365 + 89) * 24 * 60 * 60 * 1000000
71 // 89 is the number of leap years between 1970 and 1601.
72 const uint64 kDeltaEpochInMicroSecs = 11644473600000000ULL;
73 // Convert file time to unix epoch
74 time_value.QuadPart -= kDeltaEpochInMicroSecs;
75 *sec = static_cast<uint64>(time_value.QuadPart / 1000000UL);
76 *usec = static_cast<uint32>(time_value.QuadPart % 1000000UL);
77 #else // OS_WIN
78 struct timeval tv;
79 gettimeofday(&tv, nullptr);
80 *sec = tv.tv_sec;
81 *usec = tv.tv_usec;
82 #endif // OS_WIN
83 }
84
85 virtual uint64 GetTime() {
86 #ifdef OS_WIN
87 return static_cast<uint64>(_time64(nullptr));
88 #else
89 return static_cast<uint64>(time(nullptr));
90 #endif // OS_WIN
91 }
92
93 virtual bool GetTmWithOffsetSecond(time_t offset_sec, tm *output) {
94 const time_t current_sec = static_cast<time_t>(this->GetTime());
95 const time_t modified_sec = current_sec + offset_sec;
96
97 #ifdef OS_WIN
98 if (_localtime64_s(output, &modified_sec) != 0) {
99 return false;
100 }
101 #elif defined(__native_client__)
102 const time_t localtime_sec = modified_sec + timezone_offset_sec_;
103 if (gmtime_r(&localtime_sec, output) == nullptr) {
104 return false;
105 }
106 #else // !OS_WIN && !__native_client__
107 if (localtime_r(&modified_sec, output) == nullptr) {
108 return false;
109 }
110 #endif // OS_WIN
111 return true;
112 }
113
114 virtual uint64 GetFrequency() {
115 #if defined(OS_WIN)
116 LARGE_INTEGER timestamp;
117 // TODO(yukawa): Consider the case where QueryPerformanceCounter is not
118 // available.
119 const BOOL result = ::QueryPerformanceFrequency(&timestamp);
120 return static_cast<uint64>(timestamp.QuadPart);
121 #elif defined(OS_MACOSX)
122 static mach_timebase_info_data_t timebase_info;
123 mach_timebase_info(&timebase_info);
124 return static_cast<uint64>(
125 1.0e9 * timebase_info.denom / timebase_info.numer);
126 #elif defined(OS_LINUX)
127 return 1000000uLL;
128 #else // platforms (OS_WIN, OS_MACOSX, OS_LINUX, ...)
129 #error "Not supported platform"
130 #endif // platforms (OS_WIN, OS_MACOSX, OS_LINUX, ...)
131 }
132
133 virtual uint64 GetTicks() {
134 // TODO(team): Use functions in <chrono> once the use of it is approved.
135 #if defined(OS_WIN)
136 LARGE_INTEGER timestamp;
137 // TODO(yukawa): Consider the case where QueryPerformanceCounter is not
138 // available.
139 const BOOL result = ::QueryPerformanceCounter(&timestamp);
140 return static_cast<uint64>(timestamp.QuadPart);
141 #elif defined(OS_MACOSX)
142 return static_cast<uint64>(mach_absolute_time());
143 #elif defined(OS_LINUX)
144 uint64 sec;
145 uint32 usec;
146 GetTimeOfDay(&sec, &usec);
147 return sec * 1000000 + usec;
148 #else // platforms (OS_WIN, OS_MACOSX, OS_LINUX, ...)
149 #error "Not supported platform"
150 #endif // platforms (OS_WIN, OS_MACOSX, OS_LINUX, ...)
151 }
152
153 #ifdef __native_client__
154 virtual void SetTimezoneOffset(int32 timezone_offset_sec) {
155 timezone_offset_sec_ = timezone_offset_sec;
156 }
157
158 private:
159 int32 timezone_offset_sec_;
160 #endif // __native_client__
161 };
162
163 ClockInterface *g_clock = nullptr;
164
165 inline ClockInterface *GetClock() {
166 return g_clock != nullptr ? g_clock : Singleton<ClockImpl>::get();
167 }
168
169 } // namespace
170
171 void Clock::GetTimeOfDay(uint64 *sec, uint32 *usec) {
172 GetClock()->GetTimeOfDay(sec, usec);
173 }
174
175 uint64 Clock::GetTime() {
176 return GetClock()->GetTime();
177 }
178
179 bool Clock::GetTmWithOffsetSecond(tm *time_with_offset, int offset_sec) {
180 return GetClock()->GetTmWithOffsetSecond(offset_sec, time_with_offset);
181 }
182
183 uint64 Clock::GetFrequency() {
184 return GetClock()->GetFrequency();
185 }
186
187 uint64 Clock::GetTicks() {
188 return GetClock()->GetTicks();
189 }
190
191 #ifdef __native_client__
192 void Clock::SetTimezoneOffset(int32 timezone_offset_sec) {
193 return GetClock()->SetTimezoneOffset(timezone_offset_sec);
194 }
195 #endif // __native_client__
196
197 void Clock::SetClockForUnitTest(ClockInterface *clock) {
198 g_clock = clock;
199 }
200
201 } // namespace mozc
0 // Copyright 2010-2015, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 #ifndef MOZC_BASE_CLOCK_H_
30 #define MOZC_BASE_CLOCK_H_
31
32 #include <ctime>
33
34 #include "base/port.h"
35
36 namespace mozc {
37
38 class ClockInterface {
39 public:
40 virtual ~ClockInterface() {}
41
42 virtual void GetTimeOfDay(uint64 *sec, uint32 *usec) = 0;
43 virtual uint64 GetTime() = 0;
44 virtual bool GetTmWithOffsetSecond(time_t offset_sec, tm *output) = 0;
45
46 // High accuracy clock.
47 virtual uint64 GetFrequency() = 0;
48 virtual uint64 GetTicks() = 0;
49
50 #ifdef __native_client__
51 virtual void SetTimezoneOffset(int32 timezone_offset_sec) = 0;
52 #endif // __native_client__
53
54 protected:
55 ClockInterface() {}
56 };
57
58 class Clock {
59 public:
60 // Gets the current time using gettimeofday-like functions.
61 // sec: number of seconds from epoch
62 // usec: micro-second passed: [0,1000000)
63 static void GetTimeOfDay(uint64 *sec, uint32 *usec);
64
65 // Gets the current time using time-like function
66 // For Windows, _time64() is used.
67 // For Linux/Mac, time() is used.
68 static uint64 GetTime();
69
70 // Gets local time, which is offset_sec seconds after now. Returns true if
71 // succeeded.
72 static bool GetTmWithOffsetSecond(tm *time_with_offset, int offset_sec);
73
74 // Gets the current local time to current_time. Returns true if succeeded.
75 static bool GetCurrentTm(tm *current_time) {
76 return GetTmWithOffsetSecond(current_time, 0);
77 }
78
79 // Gets the system frequency to calculate the time from ticks.
80 static uint64 GetFrequency();
81
82 // Gets the current ticks. It may return incorrect value on Virtual Machines.
83 // If you'd like to get a value in secs, it is necessary to divide a result by
84 // GetFrequency().
85 static uint64 GetTicks();
86
87 #ifdef __native_client__
88 // Sets the time difference between local time and UTC time in seconds.
89 // We use this function in NaCl Mozc because we can't know the local timezone
90 // in NaCl environment.
91 static void SetTimezoneOffset(int32 timezone_offset_sec);
92 #endif // __native_client__
93
94 // TESTONLY: The behavior of global system clock can be overridden by using
95 // this method. Set to nullptr to restore the default clock. This method
96 // doesn't take the ownership of |clock|.
97 static void SetClockForUnitTest(ClockInterface *clock);
98
99 private:
100 DISALLOW_IMPLICIT_CONSTRUCTORS(Clock);
101 };
102
103 } // namespace mozc
104
105 #endif // MOZC_BASE_CLOCK_H_
2929 #ifndef MOZC_BASE_CLOCK_MOCK_H_
3030 #define MOZC_BASE_CLOCK_MOCK_H_
3131
32 #include <ctime>
33
32 #include "base/clock.h"
3433 #include "base/port.h"
35 #include "base/util.h"
3634
3735 namespace mozc {
3836
3937 // Standard mock clock implementation.
4038 // This mock behaves in UTC
41 class ClockMock : public Util::ClockInterface {
39 class ClockMock : public ClockInterface {
4240 public:
4341 ClockMock(uint64 sec, uint32 usec);
4442 virtual ~ClockMock();
0 // Copyright 2010-2015, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 #include "base/clock.h"
30
31 #include "base/clock_mock.h"
32 #include "testing/base/public/gunit.h"
33
34 namespace mozc {
35 namespace {
36
37 // 2020-12-23 13:24:35 (Wed) UTC
38 // 123456 [usec]
39 const uint64 kTestSeconds = 1608729875uLL;
40 const uint32 kTestMicroSeconds = 123456u;
41
42 TEST(ClockTest, TimeTestWithMock) {
43 ClockMock clock_mock(kTestSeconds, kTestMicroSeconds);
44 Clock::SetClockForUnitTest(&clock_mock);
45
46 // GetTime
47 {
48 EXPECT_EQ(kTestSeconds, Clock::GetTime());
49 }
50
51 // GetTimeOfDay
52 {
53 uint64 current_sec;
54 uint32 current_usec;
55 Clock::GetTimeOfDay(&current_sec, &current_usec);
56 EXPECT_EQ(kTestSeconds, current_sec);
57 EXPECT_EQ(kTestMicroSeconds, current_usec);
58 }
59
60 // GetCurrentTm
61 // 2020-12-23 13:24:35 (Wed)
62 {
63 tm current_tm;
64 Clock::GetCurrentTm(&current_tm);
65 EXPECT_EQ(120, current_tm.tm_year);
66 EXPECT_EQ(11, current_tm.tm_mon);
67 EXPECT_EQ(23, current_tm.tm_mday);
68 EXPECT_EQ(13, current_tm.tm_hour);
69 EXPECT_EQ(24, current_tm.tm_min);
70 EXPECT_EQ(35, current_tm.tm_sec);
71 EXPECT_EQ(3, current_tm.tm_wday);
72 }
73
74 // GetTmWithoutOffsetSecond
75 // 2024/02/23 23:11:15 (Fri)
76 {
77 const int offset_seconds = 100000000;
78 tm offset_tm;
79 Clock::GetTmWithOffsetSecond(&offset_tm, offset_seconds);
80 EXPECT_EQ(124, offset_tm.tm_year);
81 EXPECT_EQ(1, offset_tm.tm_mon);
82 EXPECT_EQ(23, offset_tm.tm_mday);
83 EXPECT_EQ(23, offset_tm.tm_hour);
84 EXPECT_EQ(11, offset_tm.tm_min);
85 EXPECT_EQ(15, offset_tm.tm_sec);
86 EXPECT_EQ(5, offset_tm.tm_wday);
87 }
88
89 // GetFrequency / GetTicks
90 {
91 const uint64 kFrequency = 12345;
92 const uint64 kTicks = 54321;
93 clock_mock.SetFrequency(kFrequency);
94 EXPECT_EQ(kFrequency, Clock::GetFrequency());
95 clock_mock.SetTicks(kTicks);
96 EXPECT_EQ(kTicks, Clock::GetTicks());
97 }
98
99 // Restore the default clock
100 Clock::SetClockForUnitTest(nullptr);
101
102 // GetFrequency / GetTicks without ClockMock
103 {
104 EXPECT_NE(0, Clock::GetFrequency());
105 EXPECT_NE(0, Clock::GetTicks());
106 }
107 }
108
109 TEST(ClockTest, TimeTestWithoutMock) {
110 uint64 get_time_of_day_sec, get_time_sec;
111 uint32 get_time_of_day_usec;
112
113 Clock::GetTimeOfDay(&get_time_of_day_sec, &get_time_of_day_usec);
114 get_time_sec = Clock::GetTime();
115
116 // hmm, unstable test.
117 const int margin = 1;
118 EXPECT_NEAR(get_time_of_day_sec, get_time_sec, margin)
119 << ": This test have possibilities to fail "
120 << "when system is busy and slow.";
121 }
122
123 } // namespace
124 } // namespace mozc
5252 #ifdef OS_ANDROID
5353 #include "base/const.h"
5454 #endif // OS_ANDROID
55 #include "base/clock.h"
5556 #include "base/file_stream.h"
5657 #include "base/file_util.h"
5758 #include "base/flags.h"
5859 #include "base/mutex.h"
5960 #include "base/singleton.h"
6061 #include "base/system_util.h"
61 #include "base/util.h"
6262
6363 DEFINE_bool(colored_log, true, "Enables colored log messages on tty devices");
6464 DEFINE_bool(logtostderr,
102102 string Logging::GetLogMessageHeader() {
103103 #ifndef OS_ANDROID
104104 tm tm_time;
105 Util::GetCurrentTm(&tm_time);
105 Clock::GetCurrentTm(&tm_time);
106106
107107 char buf[512];
108108 snprintf(buf, sizeof(buf),
2626 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
29 #include <string.h>
29 #include "base/mutex.h"
30
31 #include "base/clock.h"
3032 #include "base/logging.h"
31 #include "base/mutex.h"
3233 #include "base/thread.h"
34 #include "base/thread_annotations.h"
3335 #include "base/util.h"
3436 #include "testing/base/public/gunit.h"
3537
130132
131133 uint64 start_sec;
132134 uint32 start_usec;
133 Util::GetTimeOfDay(&start_sec, &start_usec);
135 Clock::GetTimeOfDay(&start_sec, &start_usec);
134136 t.Start();
135137
136138 Util::Sleep(100);
141143
142144 uint64 end_sec;
143145 uint32 end_usec;
144 Util::GetTimeOfDay(&end_sec, &end_usec);
146 Clock::GetTimeOfDay(&end_sec, &end_usec);
145147 const uint64 elapsed_usec =
146148 (end_sec - start_sec) * 1000000 + end_usec - start_usec;
147149 EXPECT_GE(1000000, elapsed_usec);
3232 #include <map>
3333 #include <utility>
3434
35 #include "base/clock.h"
3536 #include "base/logging.h"
3637 #include "base/mutex.h"
3738 #include "base/port.h"
142143 class SchedulerImpl : public Scheduler::SchedulerInterface {
143144 public:
144145 SchedulerImpl() {
145 Util::SetRandomSeed(static_cast<uint32>(Util::GetTime()));
146 Util::SetRandomSeed(static_cast<uint32>(Clock::GetTime()));
146147 }
147148
148149 virtual ~SchedulerImpl() {
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
2929 #include "base/stopwatch.h"
30 #include "base/util.h"
30
31 #include "base/clock.h"
3132
3233 namespace mozc {
34
3335 Stopwatch Stopwatch::StartNew() {
3436 Stopwatch stopwatch = Stopwatch();
3537 stopwatch.Start();
4143 frequency_(1000),
4244 start_timestamp_(0),
4345 elapsed_timestamp_(0) {
44 frequency_ = Util::GetFrequency();
46 frequency_ = Clock::GetFrequency();
4547
4648 Reset();
4749 }
5355
5456 void Stopwatch::Start() {
5557 if (state_ == STOPWATCH_STOPPED) {
56 start_timestamp_ = Util::GetTicks();
58 start_timestamp_ = Clock::GetTicks();
5759 state_ = STOPWATCH_RUNNING;
5860 }
5961 }
6062
6163 void Stopwatch::Stop() {
6264 if (state_ == STOPWATCH_RUNNING) {
63 const int64 stop_timestamp = Util::GetTicks();
65 const int64 stop_timestamp = Clock::GetTicks();
6466 elapsed_timestamp_ += (stop_timestamp - start_timestamp_);
6567 start_timestamp_ = 0;
6668 state_ = STOPWATCH_STOPPED;
8486 return elapsed_timestamp_;
8587 }
8688
87 const int64 current_timestamp = Util::GetTicks();
89 const int64 current_timestamp = Clock::GetTicks();
8890 elapsed_timestamp_ += (current_timestamp - start_timestamp_);
8991 start_timestamp_ = current_timestamp;
9092
9496 bool Stopwatch::IsRunning() const {
9597 return state_ == STOPWATCH_RUNNING;
9698 }
99
97100 } // namespace mozc
2626 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
29 #include "base/stopwatch.h"
30
2931 #include <numeric>
3032
33 #include "base/clock.h"
3134 #include "base/clock_mock.h"
3235 #include "base/scoped_ptr.h"
33 #include "base/stopwatch.h"
34 #include "base/util.h"
35 #include "testing/base/public/googletest.h"
3636 #include "testing/base/public/gunit.h"
3737
3838 namespace mozc {
4343 clock_mock_.reset(new ClockMock(0, 0));
4444 // 1GHz (Accuracy = 1ns)
4545 clock_mock_->SetFrequency(1000000000uLL);
46 Util::SetClockHandler(clock_mock_.get());
46 Clock::SetClockForUnitTest(clock_mock_.get());
4747 }
4848
4949 void TearDown() {
50 Util::SetClockHandler(NULL);
50 Clock::SetClockForUnitTest(nullptr);
5151 }
5252
5353 void PutForwardNanoseconds(uint64 nano_sec) {
10361036 ::srand(seed);
10371037 }
10381038
1039 namespace {
1040 class ClockImpl : public Util::ClockInterface {
1041 public:
1042 #ifndef __native_client__
1043 ClockImpl() {}
1044 #else // __native_client__
1045 ClockImpl() : timezone_offset_sec_(0) {}
1046 #endif // __native_client__
1047 virtual ~ClockImpl() {}
1048
1049 virtual void GetTimeOfDay(uint64 *sec, uint32 *usec) {
1050 #ifdef OS_WIN
1051 FILETIME file_time;
1052 GetSystemTimeAsFileTime(&file_time);
1053 ULARGE_INTEGER time_value;
1054 time_value.HighPart = file_time.dwHighDateTime;
1055 time_value.LowPart = file_time.dwLowDateTime;
1056 // Convert into microseconds
1057 time_value.QuadPart /= 10;
1058 // kDeltaEpochInMicroSecs is difference between January 1, 1970 and
1059 // January 1, 1601 in microsecond.
1060 // This number is calculated as follows.
1061 // ((1970 - 1601) * 365 + 89) * 24 * 60 * 60 * 1000000
1062 // 89 is the number of leap years between 1970 and 1601.
1063 const uint64 kDeltaEpochInMicroSecs = 11644473600000000ULL;
1064 // Convert file time to unix epoch
1065 time_value.QuadPart -= kDeltaEpochInMicroSecs;
1066 *sec = static_cast<uint64>(time_value.QuadPart / 1000000UL);
1067 *usec = static_cast<uint32>(time_value.QuadPart % 1000000UL);
1068 #else // OS_WIN
1069 struct timeval tv;
1070 gettimeofday(&tv, NULL);
1071 *sec = tv.tv_sec;
1072 *usec = tv.tv_usec;
1073 #endif // OS_WIN
1074 }
1075
1076 virtual uint64 GetTime() {
1077 #ifdef OS_WIN
1078 return static_cast<uint64>(_time64(NULL));
1079 #else
1080 return static_cast<uint64>(time(NULL));
1081 #endif // OS_WIN
1082 }
1083
1084 virtual bool GetTmWithOffsetSecond(time_t offset_sec, tm *output) {
1085 const time_t current_sec = static_cast<time_t>(this->GetTime());
1086 const time_t modified_sec = current_sec + offset_sec;
1087
1088 #ifdef OS_WIN
1089 if (_localtime64_s(output, &modified_sec) != 0) {
1090 return false;
1091 }
1092 #elif defined(__native_client__)
1093 const time_t localtime_sec = modified_sec + timezone_offset_sec_;
1094 if (gmtime_r(&localtime_sec, output) == NULL) {
1095 return false;
1096 }
1097 #else // !OS_WIN && !__native_client__
1098 if (localtime_r(&modified_sec, output) == NULL) {
1099 return false;
1100 }
1101 #endif // OS_WIN
1102 return true;
1103 }
1104
1105 virtual uint64 GetFrequency() {
1106 #if defined(OS_WIN)
1107 LARGE_INTEGER timestamp;
1108 // TODO(yukawa): Consider the case where QueryPerformanceCounter is not
1109 // available.
1110 const BOOL result = ::QueryPerformanceFrequency(&timestamp);
1111 return static_cast<uint64>(timestamp.QuadPart);
1112 #elif defined(OS_MACOSX)
1113 static mach_timebase_info_data_t timebase_info;
1114 mach_timebase_info(&timebase_info);
1115 return static_cast<uint64>(
1116 1.0e9 * timebase_info.denom / timebase_info.numer);
1117 #elif defined(OS_LINUX)
1118 return 1000000uLL;
1119 #else // platforms (OS_WIN, OS_MACOSX, OS_LINUX, ...)
1120 #error "Not supported platform"
1121 #endif // platforms (OS_WIN, OS_MACOSX, OS_LINUX, ...)
1122 }
1123
1124 virtual uint64 GetTicks() {
1125 // TODO(team): Use functions in <chrono> once the use of it is approved.
1126 #if defined(OS_WIN)
1127 LARGE_INTEGER timestamp;
1128 // TODO(yukawa): Consider the case where QueryPerformanceCounter is not
1129 // available.
1130 const BOOL result = ::QueryPerformanceCounter(&timestamp);
1131 return static_cast<uint64>(timestamp.QuadPart);
1132 #elif defined(OS_MACOSX)
1133 return static_cast<uint64>(mach_absolute_time());
1134 #elif defined(OS_LINUX)
1135 uint64 sec;
1136 uint32 usec;
1137 GetTimeOfDay(&sec, &usec);
1138 return sec * 1000000 + usec;
1139 #else // platforms (OS_WIN, OS_MACOSX, OS_LINUX, ...)
1140 #error "Not supported platform"
1141 #endif // platforms (OS_WIN, OS_MACOSX, OS_LINUX, ...)
1142 }
1143
1144 #ifdef __native_client__
1145 virtual void SetTimezoneOffset(int32 timezone_offset_sec) {
1146 timezone_offset_sec_ = timezone_offset_sec;
1147 }
1148
1149 private:
1150 int32 timezone_offset_sec_;
1151 #endif // __native_client__
1152 };
1153
1154 Util::ClockInterface *g_clock_handler = NULL;
1155
1156 Util::ClockInterface *GetClockHandler() {
1157 if (g_clock_handler != NULL) {
1158 return g_clock_handler;
1159 } else {
1160 return Singleton<ClockImpl>::get();
1161 }
1162 }
1163
1164 } // namespace
1165
1166 void Util::SetClockHandler(Util::ClockInterface *handler) {
1167 g_clock_handler = handler;
1168 }
1169
1170 void Util::GetTimeOfDay(uint64 *sec, uint32 *usec) {
1171 GetClockHandler()->GetTimeOfDay(sec, usec);
1172 }
1173
1174 uint64 Util::GetTime() {
1175 return GetClockHandler()->GetTime();
1176 }
1177
1178 bool Util::GetCurrentTm(tm *current_time) {
1179 return GetTmWithOffsetSecond(current_time, 0);
1180 }
1181
1182 bool Util::GetTmWithOffsetSecond(tm *time_with_offset, int offset_sec) {
1183 return GetClockHandler()->GetTmWithOffsetSecond(offset_sec, time_with_offset);
1184 }
1185
1186 uint64 Util::GetFrequency() {
1187 return GetClockHandler()->GetFrequency();
1188 }
1189
1190 uint64 Util::GetTicks() {
1191 return GetClockHandler()->GetTicks();
1192 }
1193
11941039 void Util::Sleep(uint32 msec) {
11951040 #ifdef OS_WIN
11961041 ::Sleep(msec);
11981043 usleep(msec * 1000);
11991044 #endif // OS_WIN
12001045 }
1201
1202 #ifdef __native_client__
1203 void Util::SetTimezoneOffset(int32 timezone_offset_sec) {
1204 return GetClockHandler()->SetTimezoneOffset(timezone_offset_sec);
1205 }
1206 #endif // __native_client__
12071046
12081047 namespace {
12091048
280280
281281 // Set the seed of Util::Random().
282282 static void SetRandomSeed(uint32 seed);
283
284 // Get the current time info using gettimeofday-like functions.
285 // sec: number of seconds from epoch
286 // usec: micro-second passed: [0,1000000)
287 static void GetTimeOfDay(uint64 *sec, uint32 *usec);
288
289 // Get the current time info using time-like function
290 // For Windows, _time64() is used.
291 // For Linux/Mac, time() is used.
292 static uint64 GetTime();
293
294 // Get the current local time to current_time. Returns true if succeeded.
295 static bool GetCurrentTm(tm *current_time);
296 // Get local time, which is offset_sec seconds after now. Returns true if
297 // succeeded.
298 static bool GetTmWithOffsetSecond(tm *time_with_offset, int offset_sec);
299
300 // Get the system frequency to calculate the time from ticks.
301 static uint64 GetFrequency();
302
303 // Get the current ticks. It may return incorrect value on Virtual Machines.
304 // If you'd like to get a value in secs, it is necessary to divide a result by
305 // GetFrequency().
306 static uint64 GetTicks();
307
308 #ifdef __native_client__
309 // Sets the time difference between local time and UTC time in seconds.
310 // We use this function in NaCl Mozc because we can't know the local timezone
311 // in NaCl environment.
312 static void SetTimezoneOffset(int32 timezone_offset_sec);
313 #endif // __native_client__
314
315 // Interface of the helper class.
316 // Default implementation is defined in the .cc file.
317 class ClockInterface {
318 public:
319 virtual ~ClockInterface() {}
320 virtual void GetTimeOfDay(uint64 *sec, uint32 *usec) = 0;
321 virtual uint64 GetTime() = 0;
322 virtual bool GetTmWithOffsetSecond(time_t offset_sec, tm *output) = 0;
323
324 // High accuracy clock.
325 virtual uint64 GetFrequency() = 0;
326 virtual uint64 GetTicks() = 0;
327 #ifdef __native_client__
328 virtual void SetTimezoneOffset(int32 timezone_offset_sec) = 0;
329 #endif // __native_client__
330 };
331
332 // This function is provided for test.
333 // The behavior of system clock can be customized by replacing this handler.
334 static void SetClockHandler(Util::ClockInterface *handler);
335283
336284 // Suspends the execution of the current thread until
337285 // the time-out interval elapses.
3131 #include <climits>
3232 #include <cstdlib>
3333 #include <cstring>
34 #include <ctime>
3534 #include <map>
3635 #include <sstream>
3736 #include <string>
3837
39 #include "base/clock_mock.h"
4038 #include "base/compiler_specific.h"
4139 #include "base/file_stream.h"
4240 #include "base/file_util.h"
14921490 line = "line\n\n\n";
14931491 EXPECT_TRUE(Util::ChopReturns(&line));
14941492 EXPECT_EQ("line", line);
1495 }
1496
1497 // 2020-12-23 13:24:35 (Wed) UTC
1498 // 123456 [usec]
1499 const uint64 kTestSeconds = 1608729875uLL;
1500 const uint32 kTestMicroSeconds = 123456u;
1501
1502 // time utility test with mock clock
1503 TEST(UtilTest, TimeTestWithMock) {
1504 scoped_ptr<ClockMock> mock_clock(
1505 new ClockMock(kTestSeconds, kTestMicroSeconds));
1506 Util::SetClockHandler(mock_clock.get());
1507
1508 // GetTime,
1509 {
1510 EXPECT_EQ(kTestSeconds, Util::GetTime());
1511 }
1512
1513 // GetTimeOfDay
1514 {
1515 uint64 current_sec;
1516 uint32 current_usec;
1517 Util::GetTimeOfDay(&current_sec, &current_usec);
1518 EXPECT_EQ(kTestSeconds, current_sec);
1519 EXPECT_EQ(kTestMicroSeconds, current_usec);
1520 }
1521
1522 // GetCurrentTm
1523 // 2020-12-23 13:24:35 (Wed)
1524 {
1525 tm current_tm;
1526 Util::GetCurrentTm(&current_tm);
1527 EXPECT_EQ(120, current_tm.tm_year);
1528 EXPECT_EQ(11, current_tm.tm_mon);
1529 EXPECT_EQ(23, current_tm.tm_mday);
1530 EXPECT_EQ(13, current_tm.tm_hour);
1531 EXPECT_EQ(24, current_tm.tm_min);
1532 EXPECT_EQ(35, current_tm.tm_sec);
1533 EXPECT_EQ(3, current_tm.tm_wday);
1534 }
1535
1536 // GetTmWithoutOffsetSecond
1537 // 2024/02/23 23:11:15 (Fri)
1538 {
1539 const int offset_seconds = 100000000;
1540 tm offset_tm;
1541 Util::GetTmWithOffsetSecond(&offset_tm, offset_seconds);
1542 EXPECT_EQ(124, offset_tm.tm_year);
1543 EXPECT_EQ(1, offset_tm.tm_mon);
1544 EXPECT_EQ(23, offset_tm.tm_mday);
1545 EXPECT_EQ(23, offset_tm.tm_hour);
1546 EXPECT_EQ(11, offset_tm.tm_min);
1547 EXPECT_EQ(15, offset_tm.tm_sec);
1548 EXPECT_EQ(5, offset_tm.tm_wday);
1549 }
1550
1551 // GetFrequency / GetTicks
1552 {
1553 const uint64 kFrequency = 12345;
1554 const uint64 kTicks = 54321;
1555 mock_clock->SetFrequency(kFrequency);
1556 EXPECT_EQ(kFrequency, Util::GetFrequency());
1557 mock_clock->SetTicks(kTicks);
1558 EXPECT_EQ(kTicks, Util::GetTicks());
1559 }
1560
1561 // unset clock handler
1562 Util::SetClockHandler(NULL);
1563
1564 // GetFrequency / GetTicks without ClockMock
1565 {
1566 EXPECT_NE(0, Util::GetFrequency());
1567 EXPECT_NE(0, Util::GetTicks());
1568 }
1569 }
1570
1571 // time utility test without mock clock
1572 TEST(UtilTest, TimeTestWithoutMock) {
1573 uint64 get_time_of_day_sec, get_time_sec;
1574 uint32 get_time_of_day_usec;
1575
1576 Util::GetTimeOfDay(&get_time_of_day_sec, &get_time_of_day_usec);
1577 get_time_sec = Util::GetTime();
1578
1579 // hmm, unstable test.
1580 const int margin = 1;
1581 EXPECT_NEAR(get_time_of_day_sec, get_time_sec, margin)
1582 << ": This test have possibilities to fail "
1583 << "when system is busy and slow.";
15841493 }
15851494
15861495 TEST(UtilTest, EncodeURI) {
3636 #include <queue>
3737 #include <string>
3838
39 #include "base/clock.h"
3940 #include "base/flags.h"
4041 #include "base/logging.h"
4142 #include "base/mutex.h"
169170 }
170171
171172 virtual void Run() {
172 Util::SetRandomSeed(static_cast<uint32>(Util::GetTime()));
173 Util::SetRandomSeed(static_cast<uint32>(Clock::GetTime()));
173174 RegisterPepperInstanceForHTTPClient(instance_);
174175 #ifdef GOOGLE_JAPANESE_INPUT_BUILD
175176 const bool filesystem_available =
3232
3333 #include <algorithm>
3434
35 #include "base/clock.h"
3536 #include "base/config_file_stream.h"
3637 #include "base/logging.h"
3738 #include "base/number_util.h"
3940 #include "base/scoped_ptr.h"
4041 #include "base/singleton.h"
4142 #include "base/system_util.h"
42 #include "base/util.h"
4343 #include "base/version.h"
4444 #include "protocol/config.pb.h"
4545
322322 void ConfigHandler::SetMetaData(Config *config) {
323323 GeneralConfig *general_config = config->mutable_general_config();
324324 general_config->set_config_version(CONFIG_VERSION);
325 general_config->set_last_modified_time(Util::GetTime());
325 general_config->set_last_modified_time(Clock::GetTime());
326326 general_config->set_last_modified_product_version(Version::GetMozcVersion());
327327 general_config->set_platform(SystemUtil::GetOSVersionString());
328328 }
3131 #include <algorithm>
3232 #include <climits>
3333
34 #include "base/clock.h"
3435 #include "base/file_stream.h"
3536 #include "base/hash.h"
3637 #include "base/logging.h"
3232 #include <QtCore/QMutexLocker>
3333 #include <QtGui/QtGui>
3434
35 #include "base/clock.h"
3536 #include "base/logging.h"
36 #include "base/util.h"
3737 #include "config/stats_config_util.h"
3838
3939 namespace {
9494 void HandWritingThread::SetStrokes(const handwriting::Strokes &strokes) {
9595 CopyStrokes(strokes, &strokes_, &strokes_mutex_);
9696 // This is absolutely thread-unsafe but practically no problems.
97 Util::GetTimeOfDay(&strokes_sec_, &strokes_usec_);
97 Clock::GetTimeOfDay(&strokes_sec_, &strokes_usec_);
9898 }
9999
100100 void HandWritingThread::GetCandidates(vector<string> *candidates) {
2828
2929 #include "ipc/process_watch_dog.h"
3030
31 #include "base/clock.h"
3132 #include "base/logging.h"
3233 #include "base/port.h"
3334 #include "base/util.h"
4243 public:
4344 void Signaled(ProcessWatchDog::SignalType type) {
4445 EXPECT_EQ(type, ProcessWatchDog::PROCESS_SIGNALED);
45 const uint64 diff = Util::GetTime() - g_current_time;
46 const uint64 diff = Clock::GetTime() - g_current_time;
4647 EXPECT_EQ(2, diff); // allow 1-sec error
4748 }
4849 };
4950
5051 TEST(ProcessWatchDog, ProcessWatchDogTest) {
51 g_current_time = Util::GetTime();
52 g_current_time = Clock::GetTime();
5253
5354 #ifndef OS_WIN
5455 // revoke myself with different parameter
00 MAJOR=2
11 MINOR=17
2 BUILD=2144
2 BUILD=2145
33 REVISION=102
44 # NACL_DICTIONARY_VERSION is the target version of the system dictionary to be
55 # downloaded by NaCl Mozc.
3434 #include <string>
3535 #include <unordered_set>
3636
37 #include "base/clock.h"
3738 #include "base/config_file_stream.h"
3839 #include "base/flags.h"
3940 #include "base/hash.h"
15431544 return;
15441545 }
15451546
1546 const uint64 last_access_time = Util::GetTime();
1547 const uint64 last_access_time = Clock::GetTime();
15471548 const uint32 dic_key = Fingerprint("", "", type);
15481549
15491550 CHECK(dic_.get());
16531654 }
16541655
16551656 const bool is_suggestion = segments->request_type() != Segments::CONVERSION;
1656 const uint64 last_access_time = Util::GetTime();
1657 const uint64 last_access_time = Clock::GetTime();
16571658
16581659 // If user inputs a punctuation just after some long sentence,
16591660 // we make a new candidate by concatinating the top element in LRU and
3232 #include <climits>
3333 #include <string>
3434
35 #include "base/clock.h"
3536 #include "base/logging.h"
3637 #include "base/mutex.h"
3738 #include "base/process.h"
9495 case RendererLauncher::RENDERER_TIMEOUT:
9596 case RendererLauncher::RENDERER_TERMINATED:
9697 if (error_times_ <= kMaxErrorTimes &&
97 Util::GetTime() - last_launch_time_ >= kRetryIntervalTime) {
98 Clock::GetTime() - last_launch_time_ >= kRetryIntervalTime) {
9899 return true;
99100 }
100101 VLOG(1) << "never re-launch renderer";
126127 }
127128
128129 void Run() {
129 last_launch_time_ = Util::GetTime();
130 last_launch_time_ = Clock::GetTime();
130131
131132 NamedEventListener listener(name_.c_str());
132133 const bool listener_is_available = listener.IsAvailable();
4242 #include <string>
4343 #include <vector>
4444
45 #include "base/clock.h"
4546 #include "base/logging.h"
4647 #include "base/number_util.h"
4748 #include "base/util.h"
18621863 // Checks given date is valid or not in this year
18631864 bool IsValidDateInThisYear(uint32 month, uint32 day) {
18641865 struct tm t_st;
1865 if (!Util::GetTmWithOffsetSecond(&t_st, 0)) {
1866 if (!Clock::GetTmWithOffsetSecond(&t_st, 0)) {
18661867 LOG(ERROR) << "GetTmWithOffsetSecond() failed";
18671868 return false;
18681869 }
20252026 vector<string> era;
20262027 switch (type) {
20272028 case REWRITE_DATE: {
2028 if (!Util::GetTmWithOffsetSecond(&t_st, diff * 86400)) {
2029 if (!Clock::GetTmWithOffsetSecond(&t_st, diff * 86400)) {
20292030 LOG(ERROR) << "GetTmWithOffsetSecond() failed";
20302031 return false;
20312032 }
20502051 }
20512052
20522053 case REWRITE_MONTH: {
2053 if (!Util::GetCurrentTm(&t_st)) {
2054 if (!Clock::GetCurrentTm(&t_st)) {
20542055 LOG(ERROR) << "GetCurrentTm failed";
20552056 return false;
20562057 }
20642065 }
20652066
20662067 case REWRITE_YEAR: {
2067 if (!Util::GetCurrentTm(&t_st)) {
2068 if (!Clock::GetCurrentTm(&t_st)) {
20682069 LOG(ERROR) << "GetCurrentTm failed";
20692070 return false;
20702071 }
20842085 }
20852086
20862087 case REWRITE_CURRENT_TIME: {
2087 if (!Util::GetCurrentTm(&t_st)) {
2088 if (!Clock::GetCurrentTm(&t_st)) {
20882089 LOG(ERROR) << "GetCurrentTm failed";
20892090 return false;
20902091 }
20982099 }
20992100
21002101 case REWRITE_DATE_AND_CURRENT_TIME: {
2101 if (!Util::GetCurrentTm(&t_st)) {
2102 if (!Clock::GetCurrentTm(&t_st)) {
21022103 LOG(ERROR) << "GetCurrentTm failed";
21032104 return false;
21042105 }
21652166
21662167 bool DateRewriter::RewriteWeekday(Segment *segment) const {
21672168 struct tm t_st;
2168 if (!Util::GetCurrentTm(&t_st)) {
2169 if (!Clock::GetCurrentTm(&t_st)) {
21692170 LOG(ERROR) << "GetCurrentTm failed";
21702171 return false;
21712172 }
3030
3131 #include <cstddef>
3232
33 #include "base/clock.h"
3334 #include "base/clock_mock.h"
3435 #include "base/port.h"
3536 #include "base/scoped_ptr.h"
221222 TEST_F(DateRewriterTest, DateRewriteTest) {
222223 scoped_ptr<ClockMock> mock_clock(
223224 new ClockMock(kTestSeconds, kTestMicroSeconds));
224 Util::SetClockHandler(mock_clock.get());
225 Clock::SetClockForUnitTest(mock_clock.get());
225226
226227 DateRewriter rewriter;
227228 Segments segments;
470471 }
471472 }
472473
473 Util::SetClockHandler(NULL);
474 Clock::SetClockForUnitTest(nullptr);
474475 }
475476
476477 TEST_F(DateRewriterTest, ADToERA) {
3232 #include <ctime>
3333 #include <string>
3434
35 #include "base/clock.h"
3536 #include "base/logging.h"
3637 #include "base/singleton.h"
3738 #include "base/util.h"
7475 void ChangeFortune() {
7576 const int *levels = kNormalLevels;
7677 tm today;
77 if (Util::GetCurrentTm(&today)) {
78 if (Clock::GetCurrentTm(&today)) {
7879 // Modify once per one day
7980 if (today.tm_yday == last_update_yday_ &&
8081 today.tm_year == last_update_year_) {
3030
3131 #include <string>
3232
33 #include "base/clock.h"
3334 #include "base/clock_mock.h"
3435 #include "base/file_util.h"
3536 #include "base/logging.h"
161162 ConfigHandler::SetConfig(config);
162163 CharacterFormManager::GetCharacterFormManager()->Reload();
163164
164 Util::SetClockHandler(NULL);
165 Clock::SetClockForUnitTest(NULL);
165166
166167 pos_matcher_ = mock_data_manager_.GetPOSMatcher();
167168 pos_group_.reset(new PosGroup(mock_data_manager_.GetPosGroupData()));
170171 }
171172
172173 virtual void TearDown() {
173 Util::SetClockHandler(NULL);
174 Clock::SetClockForUnitTest(NULL);
174175
175176 scoped_ptr<UserSegmentHistoryRewriter> rewriter(
176177 CreateUserSegmentHistoryRewriter());
472473 const uint64 kSeconds = 0;
473474 const uint32 kMicroSeconds = 0;
474475 ClockMock clock(kSeconds, kMicroSeconds);
475 Util::SetClockHandler(&clock);
476 Clock::SetClockForUnitTest(&clock);
476477
477478 {
478479 InitSegments(&segments, 1);
576577 const uint64 kSeconds = 0;
577578 const uint32 kMicroSeconds = 0;
578579 ClockMock clock(kSeconds, kMicroSeconds);
579 Util::SetClockHandler(&clock);
580 Clock::SetClockForUnitTest(&clock);
580581
581582 {
582583 InitSegments(&segments, 1);
14701471 const uint64 kSeconds = 0;
14711472 const uint32 kMicroSeconds = 0;
14721473 ClockMock clock(kSeconds, kMicroSeconds);
1473 Util::SetClockHandler(&clock);
1474 Clock::SetClockForUnitTest(&clock);
14741475
14751476 InitSegments(&segments, 1);
14761477 segments.mutable_segment(0)->move_candidate(2, 0);
16141615 const uint64 kSeconds = 0;
16151616 const uint32 kMicroSeconds = 0;
16161617 ClockMock clock(kSeconds, kMicroSeconds);
1617 Util::SetClockHandler(&clock);
1618 Clock::SetClockForUnitTest(&clock);
16181619
16191620 rewriter->Clear();
16201621 for (int i = 0; i < 5; ++i) {
3333 #include <string>
3434 #include <vector>
3535
36 #include "base/clock.h"
3637 #include "base/logging.h"
3738 #include "base/port.h"
3839 #include "base/process.h"
218219 Session::~Session() {}
219220
220221 void Session::InitContext(ImeContext *context) const {
221 context->set_create_time(Util::GetTime());
222 context->set_create_time(Clock::GetTime());
222223 context->set_last_command_time(0);
223224 context->set_composer(new composer::Composer(NULL, &context->GetRequest()));
224225 context->set_converter(
28442845 }
28452846
28462847 void Session::UpdateTime() {
2847 context_->set_last_command_time(Util::GetTime());
2848 context_->set_last_command_time(Clock::GetTime());
28482849 }
28492850
28502851 void Session::TransformInput(commands::Input *input) {
3030
3131 #include <string>
3232
33 #include "base/clock.h"
3334 #include "base/port.h"
3435 #include "base/system_util.h"
3536 #include "base/util.h"
6465 public:
6566 SessionConverterStressTest() {
6667 if (!FLAGS_test_deterministic) {
67 FLAGS_test_srand_seed = static_cast<int32>(Util::GetTime());
68 FLAGS_test_srand_seed = static_cast<int32>(Clock::GetTime());
6869 }
6970 Util::SetRandomSeed(static_cast<uint32>(FLAGS_test_srand_seed));
7071 }
3535 #include <string>
3636 #include <vector>
3737
38 #include "base/clock.h"
3839 #include "base/flags.h"
3940 #include "base/init.h"
4041 #include "base/logging.h"
141142 SessionHandler::SessionHandler(EngineInterface *engine)
142143 : is_available_(false),
143144 max_session_size_(0),
144 last_session_empty_time_(Util::GetTime()),
145 last_session_empty_time_(Clock::GetTime()),
145146 last_cleanup_time_(0),
146147 last_create_session_time_(0),
147148 engine_(engine),
595596 const int create_session_minimum_interval =
596597 max(0, min(FLAGS_create_session_min_interval, 10));
597598
598 uint64 current_time = Util::GetTime();
599 uint64 current_time = Clock::GetTime();
599600 if (last_create_session_time_ != 0 &&
600601 (current_time - last_create_session_time_) <
601602 create_session_minimum_interval) {
641642 session->set_application_info(command->input().application_info());
642643 #ifdef __native_client__
643644 if (command->input().application_info().has_timezone_offset()) {
644 Util::SetTimezoneOffset(
645 Clock::SetTimezoneOffset(
645646 command->input().application_info().timezone_offset());
646647 }
647648 #endif // __native_client__
673674 // no active session and client doesn't send any conversion
674675 // request to the server for FLAGS_timeout sec.
675676 bool SessionHandler::Cleanup(commands::Command *command) {
676 const uint64 current_time = Util::GetTime();
677 const uint64 current_time = Clock::GetTime();
677678
678679 // suspend/hibernation may happen
679680 uint64 suspend_time = 0;
794795 // if session gets empty, save the timestamp
795796 if (last_session_empty_time_ == 0 &&
796797 session_map_->Size() == 0) {
797 last_session_empty_time_ = Util::GetTime();
798 last_session_empty_time_ = Clock::GetTime();
798799 }
799800
800801 return true;
6666 protected:
6767 virtual void SetUp() {
6868 SessionHandlerTestBase::SetUp();
69 Util::SetClockHandler(NULL);
69 Clock::SetClockForUnitTest(NULL);
7070 GenericStorageManagerFactory::SetGenericStorageManager(NULL);
7171 }
7272
7373 virtual void TearDown() {
7474 GenericStorageManagerFactory::SetGenericStorageManager(NULL);
75 Util::SetClockHandler(NULL);
75 Clock::SetClockForUnitTest(NULL);
7676 SessionHandlerTestBase::TearDown();
7777 }
7878 };
8181 uint32 expected_session_created_num = 0;
8282 const int32 interval_time = FLAGS_create_session_min_interval = 10; // 10 sec
8383 ClockMock clock(1000, 0);
84 Util::SetClockHandler(&clock);
84 Clock::SetClockForUnitTest(&clock);
8585
8686 // The oldest item is remvoed
8787 const size_t session_size = 3;
146146 TEST_F(SessionHandlerTest, CreateSessionMinInterval) {
147147 const int32 interval_time = FLAGS_create_session_min_interval = 10; // 10 sec
148148 ClockMock clock(1000, 0);
149 Util::SetClockHandler(&clock);
149 Clock::SetClockForUnitTest(&clock);
150150
151151 scoped_ptr<EngineInterface> engine(MockDataEngineFactory::Create());
152152 SessionHandler handler(engine.get());
165165 TEST_F(SessionHandlerTest, LastCreateSessionTimeout) {
166166 const int32 timeout = FLAGS_last_create_session_timeout = 10; // 10 sec
167167 ClockMock clock(1000, 0);
168 Util::SetClockHandler(&clock);
168 Clock::SetClockForUnitTest(&clock);
169169
170170 scoped_ptr<EngineInterface> engine(MockDataEngineFactory::Create());
171171 SessionHandler handler(engine.get());
182182 TEST_F(SessionHandlerTest, LastCommandTimeout) {
183183 const int32 timeout = FLAGS_last_command_timeout = 10; // 10 sec
184184 ClockMock clock(1000, 0);
185 Util::SetClockHandler(&clock);
185 Clock::SetClockForUnitTest(&clock);
186186
187187 scoped_ptr<EngineInterface> engine(MockDataEngineFactory::Create());
188188 SessionHandler handler(engine.get());
272272 uint64 id = 0;
273273
274274 ClockMock clock(1000, 0);
275 Util::SetClockHandler(&clock);
275 Clock::SetClockForUnitTest(&clock);
276276 EXPECT_TRUE(CreateSession(&handler, &id));
277277 EXPECT_TIMING_STATS("ElapsedTimeUSec", 0, 1, 0, 0);
278278 }
3333 #include <string>
3434 #include <vector>
3535
36 #include "base/clock.h"
3637 #include "base/logging.h"
3738 #include "base/mutex.h"
3839 #include "base/number_util.h"
3940 #include "base/port.h"
4041 #include "base/scheduler.h"
41 #include "base/util.h"
4242 #include "config/stats_config_util.h"
4343 #include "protocol/commands.pb.h"
4444 #include "protocol/state.pb.h"
7272 uint64 GetTimeInMilliSecond() {
7373 uint64 second = 0;
7474 uint32 micro_second = 0;
75 Util::GetTimeOfDay(&second, &micro_second);
75 Clock::GetTimeOfDay(&second, &micro_second);
7676 return second * 1000 + micro_second / 1000;
7777 }
7878
3030
3131 #include <string>
3232
33 #include "base/clock.h"
3334 #include "base/clock_mock.h"
3435 #include "base/logging.h"
3536 #include "base/scheduler.h"
5960 SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir);
6061 UsageStats::ClearAllStatsForTest();
6162
62 Util::SetClockHandler(NULL);
63 Clock::SetClockForUnitTest(nullptr);
6364
6465 scheduler_stub_.reset(new SchedulerStub);
6566 Scheduler::SetSchedulerHandler(scheduler_stub_.get());
6970 }
7071
7172 virtual void TearDown() {
72 Util::SetClockHandler(NULL);
73 Scheduler::SetSchedulerHandler(NULL);
74 config::StatsConfigUtil::SetHandler(NULL);
73 Clock::SetClockForUnitTest(nullptr);
74 Scheduler::SetSchedulerHandler(nullptr);
75 config::StatsConfigUtil::SetHandler(nullptr);
7576
7677 UsageStats::ClearAllStatsForTest();
7778 }
150151 const uint64 kSeconds = 0;
151152 const uint32 kMicroSeconds = 0;
152153 ClockMock clock(kSeconds, kMicroSeconds);
153 Util::SetClockHandler(&clock);
154 Clock::SetClockForUnitTest(&clock);
154155
155156 // prepare command
156157 commands::Command orig_show_command, orig_hide_command;
3333 #include <numeric>
3434 #include <string>
3535
36 #include "base/clock.h"
3637 #include "base/cpu_stats.h"
3738 #include "base/logging.h"
3839 #include "base/port.h"
3940 #include "base/scoped_ptr.h"
4041 #include "base/system_util.h"
4142 #include "base/unnamed_event.h"
42 #include "base/util.h"
4343 #include "client/client_interface.h"
4444
4545 namespace mozc {
137137
138138 fill(cpu_loads, cpu_loads + arraysize(cpu_loads), 0.0);
139139
140 uint64 last_cleanup_time = Util::GetTime();
140 uint64 last_cleanup_time = Clock::GetTime();
141141
142142 while (true) {
143143 VLOG(1) << "Start sleeping " << idle_interval_msec;
170170
171171 DCHECK_GT(cpu_loads_index, 0);
172172
173 const uint64 current_cleanup_time = Util::GetTime();
173 const uint64 current_cleanup_time = Clock::GetTime();
174174 if (!CanSendCleanupCommand(cpu_loads,
175175 cpu_loads_index,
176176 current_cleanup_time,
3737 #include <string>
3838 #include <vector>
3939
40 #include "base/clock.h"
4041 #include "base/file_stream.h"
4142 #include "base/file_util.h"
4243 #include "base/hash.h"
7273 }
7374
7475 void Update(char *ptr) {
75 const uint32 last_access_time = static_cast<uint32>(Util::GetTime());
76 const uint32 last_access_time = static_cast<uint32>(Clock::GetTime());
7677 memcpy(ptr + 8, reinterpret_cast<const char *>(&last_access_time), 4);
7778 }
7879
7980 void Update(char *ptr, uint64 fp, const char *value, size_t value_size) {
80 const uint32 last_access_time = static_cast<uint32>(Util::GetTime());
81 const uint32 last_access_time = static_cast<uint32>(Clock::GetTime());
8182 memcpy(ptr, reinterpret_cast<const char *>(&fp), 8);
8283 memcpy(ptr + 8, reinterpret_cast<const char *>(&last_access_time), 4);
8384 memcpy(ptr + 12, value, value_size);
3636 #include <sstream>
3737 #include <string>
3838
39 #include "base/clock.h"
3940 #include "base/const.h"
4041 #include "base/file_util.h"
4142 #include "base/flags.h"
243244 } // namespace
244245
245246 MozcEngine::MozcEngine()
246 : last_sync_time_(Util::GetTime()),
247 : last_sync_time_(Clock::GetTime()),
247248 key_event_handler_(new KeyEventHandler),
248249 client_(CreateAndConfigureClient()),
249250 #ifdef MOZC_ENABLE_X11_SELECTION_MONITOR
640641 return;
641642 }
642643
643 const uint64 current_time = Util::GetTime();
644 const uint64 current_time = Clock::GetTime();
644645 if (force ||
645646 (current_time >= last_sync_time_ &&
646647 current_time - last_sync_time_ >= kSyncDataInterval)) {
3434 #ifdef OS_ANDROID
3535 #include "base/android_util.h"
3636 #endif // OS_ANDROID
37 #include "base/clock.h"
3738 #include "base/encryptor.h"
3839 #include "base/mutex.h"
3940 #include "base/port.h"
295296
296297 bool UsageStatsUploader::Send(void *data) {
297298 const string upload_key = string(kRegistryPrefix) + kLastUploadKey;
298 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
299 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
299300 uint32 last_upload_sec = 0;
300301 const string mozc_version_key = string(kRegistryPrefix) + kMozcVersionKey;
301302 const string &current_mozc_version = Version::GetMozcVersion();
3838 #include <utility>
3939 #include <vector>
4040
41 #include "base/clock.h"
4142 #include "base/port.h"
4243 #include "base/singleton.h"
4344 #include "base/system_util.h"
215216 };
216217
217218 TEST_F(UsageStatsUploaderTest, SendTest) {
218 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
219 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
219220 const uint32 last_upload_sec = current_sec - kOneDaySec;
220221 SetUpMetaData(last_upload_sec);
221222 SetValidResult();
237238 }
238239
239240 TEST_F(UsageStatsUploaderTest, FirstTimeSendTest) {
240 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
241 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
241242 // Don't call SetUpMetaData()..
242243 SetValidResult();
243244
261262 }
262263
263264 TEST_F(UsageStatsUploaderTest, SendFailTest) {
264 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
265 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
265266 const uint32 last_upload_sec = current_sec - kHalfDaySec;
266267 SetUpMetaData(last_upload_sec);
267268 SetValidResult();
277278 }
278279
279280 TEST_F(UsageStatsUploaderTest, InvalidLastUploadTest) {
280 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
281 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
281282 // future time
282283 // for example: time zone has changed
283284 const uint32 invalid_sec = current_sec + kHalfDaySec;
296297 }
297298
298299 TEST_F(UsageStatsUploaderTest, MozcVersionMismatchTest) {
299 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
300 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
300301 const uint32 last_upload_sec = current_sec - kOneDaySec;
301302 SetUpMetaDataWithMozcVersion(last_upload_sec, "invalid_mozc_version");
302303 SetValidResult();
331332 };
332333
333334 TEST_F(UsageStatsUploaderTest, SaveMetadataFailTest) {
334 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
335 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
335336 const uint32 last_upload_sec = current_sec - kOneDaySec;
336337 const string current_version = Version::GetMozcVersion();
337338 SetUpMetaData(last_upload_sec);
364365 }
365366
366367 TEST_F(UsageStatsUploaderTest, UploadFailTest) {
367 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
368 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
368369 const uint32 last_upload_sec = current_sec - kOneDaySec;
369370 SetUpMetaData(last_upload_sec);
370371 SetValidResult();
389390 }
390391
391392 TEST_F(UsageStatsUploaderTest, UploadRetryTest) {
392 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
393 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
393394 const uint32 last_upload_sec = current_sec - kOneDaySec;
394395 SetUpMetaData(last_upload_sec);
395396 SetValidResult();
426427 }
427428
428429 TEST_F(UsageStatsUploaderTest, UploadDataTest) {
429 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
430 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
430431 const uint32 last_upload_sec = current_sec - kOneDaySec;
431432 SetUpMetaData(last_upload_sec);
432433 SetValidResult();
492493
493494 TEST_F(UsageStatsUploaderTest, UploadTouchEventStats) {
494495 // save last_upload
495 const uint32 current_sec = static_cast<uint32>(Util::GetTime());
496 const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
496497 const uint32 last_upload_sec = current_sec - kOneDaySec;
497498 SetUpMetaData(last_upload_sec);
498499 SetValidResult();
3030
3131 #include <memory>
3232
33 #include "base/clock.h"
34 #include "base/clock_mock.h"
3335 #include "testing/base/public/googletest.h"
3436 #include "testing/base/public/gunit.h"
35
36 #include "base/clock_mock.h"
37 #include "base/util.h"
3837
3938 namespace mozc {
4039 namespace win32 {
5352 clock_mock_.reset(new ClockMock(0, 0));
5453 // 1 kHz (Accuracy = 1msec)
5554 clock_mock_->SetFrequency(1000uLL);
56 Util::SetClockHandler(clock_mock_.get());
55 Clock::SetClockForUnitTest(clock_mock_.get());
5756 }
5857
5958 virtual void TearDown() {
60 Util::SetClockHandler(NULL);
59 Clock::SetClockForUnitTest(nullptr);
6160 }
6261
6362 void PutForwardMilliseconds(uint64 milli_sec) {