1 /*
2  * Copyright (C) 2023 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 <time.h>
18 #include <unistd.h>
19 #include <chrono>
20 #include <cstring>
21 #include <iostream>
22 #include <optional>
23 #include <sstream>
24 #include <unordered_map>
25 
s2ns(uint64_t s)26 uint64_t s2ns(uint64_t s) {
27     return s * 1000000000ull;
28 }
29 
PrintHelpAndExit(const std::string & error_msg="")30 void PrintHelpAndExit(const std::string& error_msg = "") {
31     int exit_error = 0;
32     if (!error_msg.empty()) {
33         std::cout << error_msg << "\n";
34         exit_error = 1;
35     }
36 
37     std::cout << "Usage: ClockTime [CLOCK_ID] [--trace]\n"
38               << "CLOCK_ID can be  CLOCK_REALTIME or CLOCK_MONOTONIC \n"
39               << "if omitted, it will obtain the processors's time-stamp counter \n"
40               << "on x86 it will use RDTSC, on arm64 it will use MRS CNTCVT. \n"
41               << "With --trace flag, it will get snapshot of the current CPU tick, ClockTime \n"
42               << "and the CPU tick per nanoseconds \n"
43               << "-h, --help      Print this help message\n";
44 
45     exit(exit_error);
46 }
47 
GetTime(int type,uint64_t * ts_ns)48 int GetTime(int type, uint64_t* ts_ns) {
49     struct timespec ts;
50     int res = clock_gettime(type, &ts);
51     if (!res) {
52         *ts_ns = s2ns(ts.tv_sec) + ts.tv_nsec;
53     }
54     return res;
55 }
56 
GetCPUTicks()57 uint64_t GetCPUTicks() {
58 #if defined(__x86_64__) || defined(__amd64__)
59     uint32_t hi, lo;
60     asm volatile("rdtsc" : "=a"(lo), "=d"(hi));
61     return ((uint64_t)lo) | (((uint64_t)hi) << 32);
62 #elif defined(__aarch64__)
63     uint64_t vct;
64     asm volatile("mrs %0, cntvct_el0" : "=r"(vct));
65     return vct;
66 #else
67     PrintHelpAndExit("GetCPUTicks() is not supported");
68     return 0;
69 #endif
70 }
71 
GetCPUTicksPerNanoSecond()72 double GetCPUTicksPerNanoSecond() {
73     uint64_t t0 = GetCPUTicks();
74     auto start = std::chrono::high_resolution_clock::now();
75     sleep(1);
76     uint64_t t1 = GetCPUTicks();
77     auto end = std::chrono::high_resolution_clock::now();
78     auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
79     return static_cast<double>(t1 - t0) / duration;
80 }
81 
GetClockId(std::string clock_name)82 clockid_t GetClockId(std::string clock_name) {
83     static std::unordered_map<std::string, clockid_t> clock_map = {
84             std::make_pair("CLOCK_REALTIME", CLOCK_REALTIME),
85             std::make_pair("CLOCK_MONOTONIC", CLOCK_MONOTONIC)};
86     auto it = clock_map.find(clock_name);
87     if (it == clock_map.end()) {
88         PrintHelpAndExit("Wrong CLOCK_ID");
89     }
90     return it->second;
91 }
92 
main(int argc,char * argv[])93 int main(int argc, char* argv[]) {
94     if (argc == 1) {
95         std::cout << GetCPUTicks() << "\n";
96     } else if (argc == 2) {
97         if (!(strcmp(argv[1], "-h") && strcmp(argv[1], "--help"))) {
98             PrintHelpAndExit();
99         }
100         uint64_t ts_ns;
101         int res = GetTime(GetClockId(argv[1]), &ts_ns);
102         if (res) {
103             std::stringstream err_msg("GetTime() got error:");
104             err_msg << res;
105             PrintHelpAndExit(err_msg.str());
106         }
107         std::cout << ts_ns << "\n";
108     } else if (argc == 3) {
109         if (strcmp(argv[2], "--trace")) {
110             PrintHelpAndExit("Wrong flag");
111         }
112         uint64_t ts_ns;
113         clockid_t clockid = GetClockId(argv[1]);
114         uint64_t cpu_tick = cpu_tick = GetCPUTicks();
115         int res = GetTime(clockid, &ts_ns);
116         if (res) {
117             std::stringstream err_msg("GetTime() got error:");
118             err_msg << res;
119             PrintHelpAndExit(err_msg.str());
120         }
121 
122         std::cout << cpu_tick << "\n";
123         std::cout << ts_ns << "\n";
124         std::cout << GetCPUTicksPerNanoSecond() << "\n";
125     } else {
126         PrintHelpAndExit("Wrong number of arguments");
127     }
128 
129     return EXIT_SUCCESS;
130 }
131