llvm-project
87 строк · 2.2 Кб
1#include "benchmark/benchmark.h"
2#include "test_macros.h"
3
4#include <mutex>
5#include <sstream>
6
7TEST_NOINLINE double istream_numbers();
8
9double istream_numbers(std::locale* loc) {
10const char* a[] = {"-6 69 -71 2.4882e-02 -100 101 -2.00005 5000000 -50000000",
11"-25 71 7 -9.3262e+01 -100 101 -2.00005 5000000 -50000000",
12"-14 53 46 -6.7026e-02 -100 101 -2.00005 5000000 -50000000"};
13
14int a1, a2, a3, a4, a5, a6, a7;
15double f1 = 0.0, f2 = 0.0, q = 0.0;
16for (int i = 0; i < 3; i++) {
17std::istringstream s(a[i]);
18if (loc)
19s.imbue(*loc);
20s >> a1 >> a2 >> a3 >> f1 >> a4 >> a5 >> f2 >> a6 >> a7;
21q += (a1 + a2 + a3 + a4 + a5 + a6 + a7 + f1 + f2) / 1000000;
22}
23return q;
24}
25
26struct LocaleSelector {
27std::locale* imbue;
28std::locale old;
29static std::mutex mutex;
30
31LocaleSelector(benchmark::State& state) {
32std::lock_guard guard(mutex);
33switch (state.range(0)) {
34case 0: {
35old = std::locale::global(std::locale::classic());
36imbue = nullptr;
37break;
38}
39case 1: {
40old = std::locale::global(std::locale::classic());
41thread_local std::locale loc("en_US.UTF-8");
42imbue = &loc;
43break;
44}
45case 2: {
46old = std::locale::global(std::locale::classic());
47static std::locale loc("en_US.UTF-8");
48imbue = &loc;
49break;
50}
51case 3: {
52old = std::locale::global(std::locale("en_US.UTF-8"));
53imbue = nullptr;
54break;
55}
56}
57}
58
59~LocaleSelector() {
60std::lock_guard guard(mutex);
61std::locale::global(old);
62}
63};
64
65std::mutex LocaleSelector::mutex;
66
67static void BM_Istream_numbers(benchmark::State& state) {
68LocaleSelector sel(state);
69double i = 0;
70while (state.KeepRunning())
71benchmark::DoNotOptimize(i += istream_numbers(sel.imbue));
72}
73BENCHMARK(BM_Istream_numbers)->DenseRange(0, 3)->UseRealTime()->Threads(1)->ThreadPerCpu();
74
75static void BM_Ostream_number(benchmark::State& state) {
76LocaleSelector sel(state);
77while (state.KeepRunning()) {
78std::ostringstream ss;
79if (sel.imbue)
80ss.imbue(*sel.imbue);
81ss << 0;
82benchmark::DoNotOptimize(ss.str().c_str());
83}
84}
85BENCHMARK(BM_Ostream_number)->DenseRange(0, 3)->UseRealTime()->Threads(1)->ThreadPerCpu();
86
87BENCHMARK_MAIN();
88