• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "perfetto/base/time.h"
18 
19 #include "gtest/gtest.h"
20 
21 namespace perfetto {
22 namespace base {
23 namespace {
24 
TEST(TimeTest,Conversions)25 TEST(TimeTest, Conversions) {
26   TimeMillis ms = GetWallTimeMs();
27   TimeNanos ns = GetWallTimeNs();
28   EXPECT_NEAR(ms.count(), ns.count() / 1000000, 1000);
29 
30   {
31     struct timespec ts = ToPosixTimespec(TimeMillis(0));
32     EXPECT_EQ(0, ts.tv_sec);
33     EXPECT_EQ(0, ts.tv_nsec);
34   }
35   {
36     struct timespec ts = ToPosixTimespec(TimeMillis(1));
37     EXPECT_EQ(0, ts.tv_sec);
38     EXPECT_EQ(1000000, ts.tv_nsec);
39   }
40   {
41     struct timespec ts = ToPosixTimespec(TimeMillis(12345));
42     EXPECT_EQ(12, ts.tv_sec);
43     EXPECT_EQ(345000000, ts.tv_nsec);
44   }
45   {
46     struct timespec ts = ToPosixTimespec(TimeMillis(1000000000001LL));
47     EXPECT_EQ(1000000000, ts.tv_sec);
48     EXPECT_EQ(1000000, ts.tv_nsec);
49   }
50 }
51 
TEST(TimeTest,GetTime)52 TEST(TimeTest, GetTime) {
53   const auto start_time = GetWallTimeNs();
54   const auto start_cputime = GetThreadCPUTimeNs();
55 
56   const unsigned ns_in_ms = 1000000;
57 
58   for (;;) {
59     auto cur_time = GetWallTimeNs();
60     auto elapsed = cur_time - start_time;
61     // Spin for a little while.
62     if (elapsed > TimeNanos(20 * ns_in_ms))
63       break;
64   }
65 
66   auto end_cputime = GetThreadCPUTimeNs();
67   auto elapsed_cputime = end_cputime - start_cputime;
68   // Check that we're not burning much more CPU time than the length of time
69   // that we spun in the loop. We may burn much less, depending on what else is
70   // happening on the test machine.
71   EXPECT_LE(elapsed_cputime.count(), 50 * ns_in_ms);
72 }
73 
74 }  // namespace
75 }  // namespace base
76 }  // namespace perfetto
77