|
5 | 5 | #include <chrono> |
6 | 6 | #include <thread> |
7 | 7 |
|
| 8 | +static inline void busy_sleep_for(std::chrono::nanoseconds duration) { |
| 9 | + auto start = std::chrono::steady_clock::now(); |
| 10 | + while ((std::chrono::steady_clock::now() - start) < duration) { |
| 11 | + // Busy-wait |
| 12 | + } |
| 13 | +} |
| 14 | + |
8 | 15 | static void BM_sleep_1us(benchmark::State& state) { |
9 | 16 | for (auto _ : state) { |
10 | | - std::this_thread::sleep_for(std::chrono::microseconds(1)); |
| 17 | + busy_sleep_for(std::chrono::microseconds(1)); |
11 | 18 | } |
12 | 19 | } |
13 | 20 | BENCHMARK(BM_sleep_1us); |
14 | 21 |
|
15 | 22 | static void BM_sleep_10us(benchmark::State& state) { |
16 | 23 | for (auto _ : state) { |
17 | | - std::this_thread::sleep_for(std::chrono::microseconds(10)); |
| 24 | + busy_sleep_for(std::chrono::microseconds(10)); |
18 | 25 | } |
19 | 26 | } |
20 | 27 | BENCHMARK(BM_sleep_10us); |
21 | 28 |
|
22 | 29 | static void BM_sleep_50us(benchmark::State& state) { |
23 | 30 | for (auto _ : state) { |
24 | | - std::this_thread::sleep_for(std::chrono::microseconds(50)); |
| 31 | + busy_sleep_for(std::chrono::microseconds(50)); |
25 | 32 | } |
26 | 33 | } |
27 | 34 | BENCHMARK(BM_sleep_50us); |
28 | 35 |
|
29 | 36 | static void BM_sleep_100us(benchmark::State& state) { |
30 | 37 | for (auto _ : state) { |
31 | | - std::this_thread::sleep_for(std::chrono::microseconds(100)); |
| 38 | + busy_sleep_for(std::chrono::microseconds(100)); |
32 | 39 | } |
33 | 40 | } |
34 | 41 | BENCHMARK(BM_sleep_100us); |
35 | 42 |
|
36 | 43 | static void BM_sleep_1ms(benchmark::State& state) { |
37 | 44 | for (auto _ : state) { |
38 | | - std::this_thread::sleep_for(std::chrono::milliseconds(1)); |
| 45 | + busy_sleep_for(std::chrono::milliseconds(1)); |
39 | 46 | } |
40 | 47 | } |
41 | 48 | BENCHMARK(BM_sleep_1ms); |
42 | 49 |
|
43 | 50 | static void BM_sleep_10ms(benchmark::State& state) { |
44 | 51 | for (auto _ : state) { |
45 | | - std::this_thread::sleep_for(std::chrono::milliseconds(10)); |
| 52 | + busy_sleep_for(std::chrono::milliseconds(10)); |
46 | 53 | } |
47 | 54 | } |
48 | 55 | BENCHMARK(BM_sleep_10ms); |
49 | 56 |
|
50 | 57 | static void BM_sleep_50ms(benchmark::State& state) { |
51 | 58 | for (auto _ : state) { |
52 | | - std::this_thread::sleep_for(std::chrono::milliseconds(50)); |
| 59 | + busy_sleep_for(std::chrono::milliseconds(50)); |
53 | 60 | } |
54 | 61 | } |
55 | 62 | BENCHMARK(BM_sleep_50ms); |
56 | 63 |
|
57 | 64 | static void BM_sleep_100ms(benchmark::State& state) { |
58 | 65 | for (auto _ : state) { |
59 | | - std::this_thread::sleep_for(std::chrono::milliseconds(100)); |
| 66 | + busy_sleep_for(std::chrono::milliseconds(100)); |
60 | 67 | } |
61 | 68 | } |
62 | 69 | BENCHMARK(BM_sleep_100ms); |
0 commit comments