Skip to content

Commit 4620e06

Browse files
committed
fixup: add busy-wait sleep
1 parent c943b12 commit 4620e06

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

examples/google_benchmark_cmake/sleep_bench.hpp

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,58 +5,65 @@
55
#include <chrono>
66
#include <thread>
77

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+
815
static void BM_sleep_1us(benchmark::State& state) {
916
for (auto _ : state) {
10-
std::this_thread::sleep_for(std::chrono::microseconds(1));
17+
busy_sleep_for(std::chrono::microseconds(1));
1118
}
1219
}
1320
BENCHMARK(BM_sleep_1us);
1421

1522
static void BM_sleep_10us(benchmark::State& state) {
1623
for (auto _ : state) {
17-
std::this_thread::sleep_for(std::chrono::microseconds(10));
24+
busy_sleep_for(std::chrono::microseconds(10));
1825
}
1926
}
2027
BENCHMARK(BM_sleep_10us);
2128

2229
static void BM_sleep_50us(benchmark::State& state) {
2330
for (auto _ : state) {
24-
std::this_thread::sleep_for(std::chrono::microseconds(50));
31+
busy_sleep_for(std::chrono::microseconds(50));
2532
}
2633
}
2734
BENCHMARK(BM_sleep_50us);
2835

2936
static void BM_sleep_100us(benchmark::State& state) {
3037
for (auto _ : state) {
31-
std::this_thread::sleep_for(std::chrono::microseconds(100));
38+
busy_sleep_for(std::chrono::microseconds(100));
3239
}
3340
}
3441
BENCHMARK(BM_sleep_100us);
3542

3643
static void BM_sleep_1ms(benchmark::State& state) {
3744
for (auto _ : state) {
38-
std::this_thread::sleep_for(std::chrono::milliseconds(1));
45+
busy_sleep_for(std::chrono::milliseconds(1));
3946
}
4047
}
4148
BENCHMARK(BM_sleep_1ms);
4249

4350
static void BM_sleep_10ms(benchmark::State& state) {
4451
for (auto _ : state) {
45-
std::this_thread::sleep_for(std::chrono::milliseconds(10));
52+
busy_sleep_for(std::chrono::milliseconds(10));
4653
}
4754
}
4855
BENCHMARK(BM_sleep_10ms);
4956

5057
static void BM_sleep_50ms(benchmark::State& state) {
5158
for (auto _ : state) {
52-
std::this_thread::sleep_for(std::chrono::milliseconds(50));
59+
busy_sleep_for(std::chrono::milliseconds(50));
5360
}
5461
}
5562
BENCHMARK(BM_sleep_50ms);
5663

5764
static void BM_sleep_100ms(benchmark::State& state) {
5865
for (auto _ : state) {
59-
std::this_thread::sleep_for(std::chrono::milliseconds(100));
66+
busy_sleep_for(std::chrono::milliseconds(100));
6067
}
6168
}
6269
BENCHMARK(BM_sleep_100ms);

0 commit comments

Comments
 (0)