1 /*
2  * Copyright (c) Facebook, Inc. and its affiliates.
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 <atomic>
18 #include <chrono>
19 
20 #include <folly/Benchmark.h>
21 #include <folly/Chrono.h>
22 #include <folly/chrono/Hardware.h>
23 #include <folly/hash/Hash.h>
24 #include <folly/init/Init.h>
25 
BENCHMARK(steady_clock_now,iters)26 BENCHMARK(steady_clock_now, iters) {
27   uint64_t r = 0;
28   while (iters--) {
29     using clock = std::chrono::steady_clock;
30     auto const s = clock::now().time_since_epoch().count();
31     r = folly::hash::twang_mix64(r ^ s);
32   }
33   folly::doNotOptimizeAway(r);
34 }
35 
BENCHMARK(coarse_steady_clock_now,iters)36 BENCHMARK(coarse_steady_clock_now, iters) {
37   uint64_t r = 0;
38   while (iters--) {
39     using clock = folly::chrono::coarse_steady_clock;
40     auto const s = clock::now().time_since_epoch().count();
41     r = folly::hash::twang_mix64(r ^ s);
42   }
43   folly::doNotOptimizeAway(r);
44 }
45 
BENCHMARK(system_clock_now,iters)46 BENCHMARK(system_clock_now, iters) {
47   uint64_t r = 0;
48   while (iters--) {
49     using clock = std::chrono::system_clock;
50     auto const s = clock::now().time_since_epoch().count();
51     r = folly::hash::twang_mix64(r ^ s);
52   }
53   folly::doNotOptimizeAway(r);
54 }
55 
BENCHMARK(coarse_system_clock_now,iters)56 BENCHMARK(coarse_system_clock_now, iters) {
57   uint64_t r = 0;
58   while (iters--) {
59     using clock = folly::chrono::coarse_system_clock;
60     auto const s = clock::now().time_since_epoch().count();
61     r = folly::hash::twang_mix64(r ^ s);
62   }
63   folly::doNotOptimizeAway(r);
64 }
65 
BENCHMARK(hardware_timestamp_unserialized,iters)66 BENCHMARK(hardware_timestamp_unserialized, iters) {
67   uint64_t r = 0;
68   while (iters--) {
69     auto const s = folly::hardware_timestamp();
70     r = folly::hash::twang_mix64(r ^ s);
71   }
72   folly::doNotOptimizeAway(r);
73 }
74 
BENCHMARK(atomic_load_relaxed,iters)75 BENCHMARK(atomic_load_relaxed, iters) {
76   std::atomic<uint64_t> now{0};
77   uint64_t r = 0;
78   while (iters--) {
79     auto const s = now.load(std::memory_order_relaxed);
80     r = folly::hash::twang_mix64(r ^ s);
81   }
82   folly::doNotOptimizeAway(r);
83 }
84 
main(int argc,char ** argv)85 int main(int argc, char** argv) {
86   folly::Init init(&argc, &argv);
87   folly::runBenchmarks();
88   return 0;
89 }
90