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 <cstring>
19 #include <iostream>
20 #include <optional>
21 #include <sstream>
22 #include <unordered_map>
23
s2ns(uint64_t s)24 uint64_t s2ns(uint64_t s) {
25 return s * 1000000000ull;
26 }
27
GetTime(int type,uint64_t * ts_ns)28 int GetTime(int type, uint64_t* ts_ns) {
29 struct timespec ts;
30 int res = clock_gettime(type, &ts);
31 if (!res) {
32 *ts_ns = s2ns(ts.tv_sec) + ts.tv_nsec;
33 }
34 return res;
35 }
36
GetCPUTicks()37 uint64_t GetCPUTicks() {
38 #if defined(__x86_64__) || defined(__amd64__)
39 uint32_t hi, lo;
40 asm volatile("rdtsc" : "=a"(lo), "=d"(hi));
41 return ((uint64_t)lo) | (((uint64_t)hi) << 32);
42 #elif defined(__aarch64__)
43 uint64_t vct;
44 asm volatile("mrs %0, cntvct_el0" : "=r"(vct));
45 return vct;
46 #else
47 #error "no cpu tick support."
48 #endif
49 }
50
PrintHelpAndExit(const std::string & error_msg="")51 void PrintHelpAndExit(const std::string& error_msg = "") {
52 int exit_error = 0;
53 if (!error_msg.empty()) {
54 std::cout << error_msg << "\n";
55 exit_error = 1;
56 }
57
58 std::cout << "Usage: ClockTime [CLOCK_ID]\n"
59 << "CLOCK_ID can be CLOCK_REALTIME or CLOCK_MONOTONIC \n"
60 << "if omitted, it will obtain the processors's time-stamp counter \n"
61 << "on x86 it will use RDTSC, on arm64 it will use MRS CNTCVT. \n"
62 << "-h, --help Print this help message\n";
63
64 exit(exit_error);
65 }
66
main(int argc,char * argv[])67 int main(int argc, char* argv[]) {
68 std::unordered_map<std::string, clockid_t> clock_map = {
69 std::make_pair("CLOCK_REALTIME", CLOCK_REALTIME),
70 std::make_pair("CLOCK_MONOTONIC", CLOCK_MONOTONIC)};
71
72 if (argc == 1) {
73 std::cout << GetCPUTicks() << "\n";
74 } else if (argc == 2) {
75 if (!(strcmp(argv[1], "-h") && strcmp(argv[1], "--help"))) {
76 PrintHelpAndExit();
77 }
78
79 uint64_t ts_ns;
80 auto it = clock_map.find(argv[1]);
81 if (it == clock_map.end()) {
82 PrintHelpAndExit("Wrong CLOCK_ID");
83 }
84
85 int res = GetTime(it->second, &ts_ns);
86 if (res) {
87 std::stringstream err_msg("GetTime() got error");
88 err_msg << res;
89 PrintHelpAndExit(err_msg.str());
90 }
91
92 std::cout << ts_ns << "\n";
93 } else {
94 PrintHelpAndExit("Wrong number of arguments");
95 }
96
97 return EXIT_SUCCESS;
98 }
99