├── .clang-format ├── .editorconfig ├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── src ├── Benchmark.cpp ├── Benchmark.h ├── CmdLineFlags.h ├── Logging.cpp ├── Logging.h └── Preprocessor.h └── test ├── CMakeLists.txt ├── hashmap_bench.cpp ├── main.cpp ├── map_find_bench.cpp └── small_map_find_bench.cpp /.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Cpp 3 | BasedOnStyle: Microsoft 4 | 5 | ColumnLimit: 120 6 | TabWidth: 4 7 | 8 | SortIncludes: false 9 | PointerAlignment: Left 10 | DerivePointerAlignment: false 11 | AllowShortLambdasOnASingleLine: Empty 12 | 13 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = crlf 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | indent_style = space 11 | indent_size = 4 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Compiled Dynamic libraries 8 | *.so 9 | *.dylib 10 | *.dll 11 | 12 | # Compiled Static libraries 13 | *.lai 14 | *.la 15 | *.a 16 | *.lib 17 | 18 | # Executables 19 | *.exe 20 | *.out 21 | *.app 22 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2014-present prototyped.cn All rights reserved. 2 | # Distributed under the terms and conditions of the Apache License. 3 | # See accompanying files LICENSE. 4 | 5 | cmake_minimum_required(VERSION 2.8) 6 | project (CppBench) 7 | 8 | set(PROJECT_ROOT_DIR ${CMAKE_SOURCE_DIR}) 9 | set(PROJECT_SRC_DIR ${PROJECT_ROOT_DIR}/src) 10 | 11 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_ROOT_DIR}/bin) 12 | 13 | if(WIN32) 14 | add_definitions(-D_WIN32_WINNT=0x0601) 15 | add_definitions(-DNOMINMAX) 16 | add_definitions(-D_SCL_SECURE_NO_WARNINGS) 17 | add_definitions(-D_CRT_SECURE_NO_WARNINGS) 18 | elseif(UNIX) 19 | add_definitions(-D__STDC_LIMIT_MACROS) 20 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -std=c++11") 21 | endif() 22 | 23 | file(GLOB_RECURSE LIB_HEADER_FILES src/*.h) 24 | file(GLOB_RECURSE LIB_SOURCE_FILES src/*.cpp) 25 | 26 | include_directories( 27 | ${PROJECT_ROOT_DIR}/src 28 | ) 29 | 30 | macro(SOURCE_GROUP_BY_DIR source_files) 31 | set(sgbd_cur_dir ${CMAKE_CURRENT_SOURCE_DIR}) 32 | foreach(sgbd_file ${${source_files}}) 33 | string(REGEX REPLACE ${sgbd_cur_dir}/\(.*\) \\1 sgbd_fpath ${sgbd_file}) 34 | string(REGEX REPLACE "\(.*\)/.*" \\1 sgbd_group_name ${sgbd_fpath}) 35 | string(COMPARE EQUAL ${sgbd_fpath} ${sgbd_group_name} sgbd_nogroup) 36 | string(REPLACE "/" "\\" sgbd_group_name ${sgbd_group_name}) 37 | if(sgbd_nogroup) 38 | set(sgbd_group_name "\\") 39 | endif(sgbd_nogroup) 40 | source_group(${sgbd_group_name} FILES ${sgbd_file}) 41 | endforeach(sgbd_file) 42 | endmacro(SOURCE_GROUP_BY_DIR) 43 | 44 | SOURCE_GROUP_BY_DIR(LIB_HEADER_FILES) 45 | SOURCE_GROUP_BY_DIR(LIB_SOURCE_FILES) 46 | 47 | add_library(libbench ${LIB_HEADER_FILES} ${LIB_SOURCE_FILES}) 48 | add_subdirectory(test) 49 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cpp-bench 2 | 3 | 4 | cpp-bench是一个非常轻量级的C++基准测试组件(benchmark component)。 5 | 6 | 这个组件取自[folly](https://github.com/facebook/folly/blob/master/folly/Benchmark.h), 7 | 并且移植到了Visual C++ 2013. 8 | 9 | 10 | 11 | 12 | ## How To Build 13 | 14 | * 安装[CMake](https://cmake.org/download/) 15 | * 使用CMake生成Visual Studio工程或者Linux Make files 16 | 17 | 18 | ## API 19 | 20 | 使用 `BENCHMARK` 宏来引入一项基准测试 21 | ~~~~~~~~cpp 22 | BENCHMARK(vectorPushBack, n) 23 | { 24 | vector v; 25 | v.push_back(42); 26 | } 27 | ~~~~~~~~ 28 | 29 | 后面所有的 `BENCHMARK_RELATIVE' 宏都以前面的benchmark为基准 30 | 31 | ~~~~~~~~cpp 32 | BENCHMARK_RELATIVE(vectorPushFront, n) 33 | { 34 | vector v; 35 | v.insert(v.begin(), 42); 36 | } 37 | ~~~~~~~~ 38 | 39 | 40 | 在`BENCHMARK_SUSPEND` 宏里面的代码不会计入基准测试时间。 41 | 42 | ~~~~~~~~cpp 43 | BENCHMARK(insertVectorBegin, n) 44 | { 45 | vector v; 46 | BENCHMARK_SUSPEND 47 | { 48 | v.reserve(n); 49 | } 50 | for(auto i = 0; i < n; i++) 51 | { 52 | v.insert(v.begin(), 42); 53 | } 54 | } 55 | ~~~~~~~~ 56 | 57 | 可以使用`BENCHMARK_DRAW_LINE` 宏画一条线。 58 | 59 | ~~~~~~~~cpp 60 | BENCHMARK_DRAW_LINE() 61 | ~~~~~~~~ 62 | 63 | 64 | ## 示例 65 | 66 | 以 [map_bench.cpp](https://github.com/ichenq/cpp-bench/blob/master/test/map_bench.cpp)为例: 67 | 它测试std::map和std::unordered_map的insert, erase, find的性能差异。 68 | 69 | 70 | 这是在我机器上测试的结果: 71 | 72 | ~~~~~~~~cpp 73 | i5-7500 3.4GHZ Windows 10 x64 (Visual C++ 2017) 74 | ============================================================================ 75 | cpp-bench\test\hashmap_bench.cpp relative time/iter iters/s 76 | ============================================================================ 77 | TreeMapInsert 3.13us 319.92K 78 | HashMapInsert 134.84% 2.32us 431.38K 79 | TreeMapDelete 3.10us 322.84K 80 | HashMapDelete 198.26% 1.56us 640.06K 81 | TreeMapIntFind 2.21us 453.43K 82 | HashMapIntFind 144.20% 1.53us 653.84K 83 | ============================================================================ 84 | 85 | E5-2630 2.3GHZ CentOS 7 x64 (GCC 5.3) 86 | ============================================================================ 87 | ../test/map_bench.cpp relative time/iter iters/s 88 | ============================================================================ 89 | TreeMapInsert 3.23us 309.40K 90 | HashMapInsert 103.37% 3.13us 319.83K 91 | TreeMapDelete 3.15us 317.05K 92 | HashMapDelete 147.78% 2.13us 468.54K 93 | TreeMapIntFind 2.16us 463.27K 94 | HashMapIntFind 138.02% 1.56us 639.42K 95 | ============================================================================ 96 | 97 | ~~~~~~~~ 98 | 99 | 100 | 说明: 101 | 102 | `relative` 表示跟基准测试对比的数值 103 | 104 | `time/iter`表示函数每次迭代消耗的时间 105 | 106 | `iters/s` 表示函数每秒可以迭代多少次 107 | 108 | 109 | 110 | [1]: https://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 111 | 112 | [2]: http://www.slideshare.net/andreialexandrescu1/three-optimization-tips-for-c-15708507 113 | -------------------------------------------------------------------------------- /src/Benchmark.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Facebook, Inc. 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 | // @author Andrei Alexandrescu (andrei.alexandrescu@fb.com) 18 | 19 | #include "Benchmark.h" 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include "Logging.h" 32 | #include "CmdLineFlags.h" 33 | 34 | #ifdef _WIN32 35 | #include 36 | #endif 37 | 38 | using namespace std; 39 | 40 | DEFINE_bool(benchmark, true, "Run benchmarks."); 41 | 42 | DEFINE_string(bm_regex, "", 43 | "Only benchmarks whose names match this regex will be run."); 44 | 45 | DEFINE_int32(bm_min_usec, 100, 46 | "Minimum # of microseconds we'll accept for each benchmark."); 47 | 48 | DEFINE_int32(bm_min_iters, 1, 49 | "Minimum # of iterations we'll try for each benchmark."); 50 | 51 | DEFINE_int32(bm_max_secs, 1, 52 | "Maximum # of seconds we'll spend on each benchmark."); 53 | 54 | 55 | BenchmarkSuspender::NanosecondsSpent BenchmarkSuspender::nsSpent; 56 | 57 | 58 | namespace { 59 | 60 | typedef function BenchmarkFun; 61 | typedef tuple BenchmarkItem; 62 | 63 | // To avoid static initialization order fiasco 64 | vector& getBenchmarks() 65 | { 66 | static vector benchmarks; 67 | return benchmarks; 68 | } 69 | 70 | vector& getBenchmarkInitializerList() 71 | { 72 | static vector initialier_list; 73 | return initialier_list; 74 | } 75 | 76 | } // anonymous namespace 77 | 78 | 79 | // Add the global baseline, do nothing but measures the overheads. 80 | BENCHMARK(globalBenchmarkBaseline, n) 81 | { 82 | #ifdef _MSC_VER 83 | _ReadWriteBarrier(); 84 | #else 85 | asm volatile(""); 86 | #endif 87 | } 88 | 89 | void detail::addBenchmarkInit(std::function initializer) 90 | { 91 | auto& init_list = getBenchmarkInitializerList(); 92 | init_list.emplace_back(initializer); 93 | } 94 | 95 | void detail::addBenchmarkImpl(const char* file, 96 | const char* name, 97 | BenchmarkFun fun) 98 | { 99 | auto item = make_tuple(file, name, fun); 100 | auto& benchmarks = getBenchmarks(); 101 | if (strcmp(name, "globalBenchmarkBaseline") == 0) 102 | { 103 | benchmarks.emplace(benchmarks.begin(), item); 104 | } 105 | else 106 | { 107 | benchmarks.emplace_back(item); 108 | } 109 | } 110 | 111 | 112 | /** 113 | * Given a bunch of benchmark samples, estimate the actual run time. 114 | */ 115 | inline double estimateTime(double * begin, double * end) 116 | { 117 | assert(begin < end); 118 | 119 | // Current state of the art: get the minimum. After some 120 | // experimentation, it seems taking the minimum is the best. 121 | return *min_element(begin, end); 122 | } 123 | 124 | 125 | static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun, const double globalBaseline) 126 | { 127 | // We choose a minimum (sic) of 100,000 nanoseconds 128 | static const auto minNanoseconds = FLAGS_bm_min_usec * 1000UL; 129 | 130 | // We do measurements in several epochs and take the minimum, to 131 | // account for jitter. 132 | static const unsigned int epochs = 1000; 133 | 134 | // We establish a total time budget as we don't want a measurement 135 | // to take too long. This will curtail the number of actual epochs. 136 | const uint64_t timeBudgetInNs = FLAGS_bm_max_secs * 1000000000; 137 | 138 | double epochResults[epochs] = { 0 }; 139 | 140 | uint64_t global = getNowTickCount(); 141 | 142 | size_t actualEpochs = 0; 143 | for (; actualEpochs < epochs; ++actualEpochs) 144 | { 145 | for (auto n = FLAGS_bm_min_iters; n < (1UL << 30); n *= 2) 146 | { 147 | auto const nsecsAndIter = fun(n); // run `n` times of benchmark case 148 | if (nsecsAndIter.first < minNanoseconds) 149 | { 150 | continue; 151 | } 152 | // We got an accurate enough timing, done. But only save if 153 | // smaller than the current result. 154 | epochResults[actualEpochs] = max(0.0, double(nsecsAndIter.first) / 155 | nsecsAndIter.second - globalBaseline); 156 | // Done with the current epoch, we got a meaningful timing. 157 | break; 158 | } 159 | if (getNowTickCount() - global >= timeBudgetInNs) 160 | { 161 | // No more time budget available. 162 | ++actualEpochs; 163 | break; 164 | } 165 | } 166 | // If the benchmark was basically drowned in baseline noise, it's 167 | // possible it became negative. 168 | return max(0.0, estimateTime(epochResults, epochResults + actualEpochs)); 169 | } 170 | 171 | static void printBenchmarkResultsAsTable( 172 | const vector >& data); 173 | 174 | 175 | void runBenchmarks() 176 | { 177 | auto& init_list = getBenchmarkInitializerList(); 178 | for (auto& func : init_list) 179 | { 180 | func(); 181 | } 182 | 183 | auto& benchmarks = getBenchmarks(); 184 | CHECK(!benchmarks.empty()); 185 | vector> results; 186 | results.reserve(benchmarks.size() - 1); 187 | 188 | unique_ptr bmRegex; 189 | if (!FLAGS_bm_regex.empty()) 190 | { 191 | bmRegex.reset(new regex(FLAGS_bm_regex)); 192 | } 193 | 194 | // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS. 195 | auto const globalBaseline = runBenchmarkGetNSPerIteration( 196 | get<2>(getBenchmarks().front()), 0); 197 | for (auto i = 1U; i < benchmarks.size(); i++) 198 | { 199 | double elapsed = 0.0; 200 | if (strcmp(get<1>(benchmarks[i]), "-") != 0) // skip separators 201 | { 202 | if (bmRegex && !regex_search(get<1>(benchmarks[i]), *bmRegex)) 203 | { 204 | continue; 205 | } 206 | elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks[i]), 207 | globalBaseline); 208 | } 209 | results.emplace_back(get<0>(benchmarks[i]), get<1>(benchmarks[i]), 210 | elapsed); 211 | } 212 | 213 | printBenchmarkResultsAsTable(results); 214 | } 215 | 216 | #ifdef _WIN32 217 | static uint64_t getPerformanceFreqency() 218 | { 219 | uint64_t freq; 220 | CHECK(QueryPerformanceFrequency((LARGE_INTEGER*)&freq)); 221 | return freq; 222 | }; 223 | #endif 224 | 225 | uint64_t getNowTickCount() 226 | { 227 | #ifdef _WIN32 228 | static uint64_t freq = getPerformanceFreqency(); 229 | uint64_t now; 230 | CHECK(QueryPerformanceCounter((LARGE_INTEGER*)&now)); 231 | return (now * 1000000000UL) / freq; 232 | #else 233 | timespec ts; 234 | CHECK(clock_gettime(CLOCK_REALTIME, &ts) == 0); 235 | return (ts.tv_sec * 1000000000UL) + ts.tv_nsec; 236 | #endif 237 | } 238 | 239 | struct ScaleInfo 240 | { 241 | double boundary; 242 | const char* suffix; 243 | }; 244 | 245 | static const ScaleInfo kTimeSuffixes[] 246 | { 247 | { 365.25 * 24 * 3600, "years" }, 248 | { 24 * 3600, "days" }, 249 | { 3600, "hr" }, 250 | { 60, "min" }, 251 | { 1, "s" }, 252 | { 1E-3, "ms" }, 253 | { 1E-6, "us" }, 254 | { 1E-9, "ns" }, 255 | { 1E-12, "ps" }, 256 | { 1E-15, "fs" }, 257 | { 0, nullptr }, 258 | }; 259 | 260 | static const ScaleInfo kMetricSuffixes[] 261 | { 262 | { 1E24, "Y" }, // yotta 263 | { 1E21, "Z" }, // zetta 264 | { 1E18, "X" }, // "exa" written with suffix 'X' so as to not create 265 | // confusion with scientific notation 266 | { 1E15, "P" }, // peta 267 | { 1E12, "T" }, // terra 268 | { 1E9, "G" }, // giga 269 | { 1E6, "M" }, // mega 270 | { 1E3, "K" }, // kilo 271 | { 1, "" }, 272 | { 1E-3, "m" }, // milli 273 | { 1E-6, "u" }, // micro 274 | { 1E-9, "n" }, // nano 275 | { 1E-12, "p" }, // pico 276 | { 1E-15, "f" }, // femto 277 | { 1E-18, "a" }, // atto 278 | { 1E-21, "z" }, // zepto 279 | { 1E-24, "y" }, // yocto 280 | { 0, nullptr }, 281 | }; 282 | 283 | static string humanReadable(double n, unsigned int decimals, const ScaleInfo* scales) 284 | { 285 | char readableString[128]; 286 | if (std::isinf(n) || std::isnan(n)) 287 | { 288 | snprintf(readableString, 128, "%f", n); 289 | return readableString; 290 | } 291 | 292 | const double absValue = fabs(n); 293 | const ScaleInfo* scale = scales; 294 | while (absValue < scale[0].boundary && scale[1].suffix != nullptr) 295 | { 296 | ++scale; 297 | } 298 | 299 | const double scaledValue = n / scale->boundary; 300 | snprintf(readableString, 128, "%.*f%s", decimals, scaledValue, scale->suffix); 301 | return readableString; 302 | } 303 | 304 | inline string readableTime(double n, unsigned int decimals) 305 | { 306 | return humanReadable(n, decimals, kTimeSuffixes); 307 | } 308 | 309 | inline string metricReadable(double n, unsigned int decimals) 310 | { 311 | return humanReadable(n, decimals, kMetricSuffixes); 312 | } 313 | 314 | void printBenchmarkResultsAsTable( 315 | const vector >& data) 316 | { 317 | // Width available 318 | static const unsigned int columns = 76; 319 | 320 | // Compute the longest benchmark name 321 | size_t longestName = 0; 322 | auto& benchmarks = getBenchmarks(); 323 | for (auto i = 1U; i < benchmarks.size(); i++) 324 | { 325 | longestName = max(longestName, strlen(get<1>(benchmarks[i]))); 326 | } 327 | 328 | // Print a horizontal rule 329 | auto separator = [&](char pad) 330 | { 331 | puts(string(columns, pad).c_str()); 332 | }; 333 | 334 | // Print header for a file 335 | auto header = [&](const char* file) 336 | { 337 | separator('='); 338 | printf("%-*s relative time/iter iters/s\n", 339 | columns - 28, file); 340 | separator('='); 341 | }; 342 | 343 | double baselineNsPerIter = numeric_limits::max(); 344 | const char* lastFile = ""; 345 | 346 | for (auto& datum : data) 347 | { 348 | auto file = get<0>(datum); 349 | if (strcmp(file, lastFile)) 350 | { 351 | // New file starting 352 | header(file); 353 | lastFile = file; 354 | } 355 | 356 | string s = get<1>(datum); 357 | if (s == "-") 358 | { 359 | separator('-'); 360 | continue; 361 | } 362 | bool useBaseline /* = void */; 363 | if (s[0] == '%') 364 | { 365 | s.erase(0, 1); 366 | useBaseline = true; 367 | } 368 | else 369 | { 370 | baselineNsPerIter = get<2>(datum); 371 | useBaseline = false; 372 | } 373 | s.resize(columns - 29, ' '); 374 | auto nsPerIter = get<2>(datum); 375 | auto secPerIter = nsPerIter / 1E9; 376 | auto itersPerSec = 1 / secPerIter; 377 | auto secPerIterReadable = readableTime(secPerIter, 2); 378 | auto itersPerSecReadable = metricReadable(itersPerSec, 2); 379 | if (!useBaseline) 380 | { 381 | // Print without baseline 382 | printf("%*s %9s %7s\n", 383 | static_cast(s.size()), s.c_str(), 384 | secPerIterReadable.c_str(), 385 | itersPerSecReadable.c_str()); 386 | } 387 | else 388 | { 389 | // Print with baseline 390 | auto rel = baselineNsPerIter / nsPerIter * 100.0; 391 | auto relReadable = metricReadable(rel, 2); 392 | printf("%*s %7s%% %9s %7s\n", 393 | static_cast(s.size()), s.c_str(), 394 | relReadable.c_str(), 395 | secPerIterReadable.c_str(), 396 | itersPerSecReadable.c_str()); 397 | } 398 | } 399 | separator('='); 400 | } 401 | -------------------------------------------------------------------------------- /src/Benchmark.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Facebook, Inc. 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 | #pragma once 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include "Preprocessor.h" 24 | 25 | 26 | 27 | /** 28 | * Runs all benchmarks defined. Usually put in main(). 29 | */ 30 | void runBenchmarks(); 31 | 32 | 33 | namespace detail { 34 | 35 | typedef std::pair TimeIterPair; 36 | 37 | /** 38 | * Adds a benchmark wrapped in a std::function. Only used 39 | * internally. Pass by value is intentional. 40 | */ 41 | void addBenchmarkImpl(const char* file, 42 | const char* name, 43 | std::function); 44 | 45 | typedef std::function BenchmarkInitializer; 46 | 47 | void addBenchmarkInit(BenchmarkInitializer initializer); 48 | 49 | } // namespace detail 50 | 51 | // Current tick count(in nanoseconds) 52 | uint64_t getNowTickCount(); 53 | 54 | 55 | 56 | /** 57 | * Supporting type for BENCHMARK_SUSPEND defined below. 58 | */ 59 | struct BenchmarkSuspender 60 | { 61 | BenchmarkSuspender() : start_(getNowTickCount()) 62 | { 63 | } 64 | 65 | BenchmarkSuspender(const BenchmarkSuspender &) = delete; 66 | BenchmarkSuspender(BenchmarkSuspender&& rhs) 67 | : start_(rhs.start_) 68 | { 69 | rhs.start_ = getNowTickCount(); 70 | } 71 | 72 | BenchmarkSuspender& operator=(const BenchmarkSuspender &) = delete; 73 | BenchmarkSuspender& operator=(BenchmarkSuspender && rhs) 74 | { 75 | start_ = rhs.start_; 76 | rhs.start_ = getNowTickCount(); 77 | return *this; 78 | } 79 | 80 | ~BenchmarkSuspender() 81 | { 82 | tally(); 83 | } 84 | 85 | void dismiss() 86 | { 87 | tally(); 88 | start_ = getNowTickCount(); 89 | } 90 | 91 | void rehire() 92 | { 93 | start_ = getNowTickCount(); 94 | } 95 | 96 | /** 97 | * This helps the macro definition. To get around the dangers of 98 | * operator bool, returns a pointer to member (which allows no 99 | * arithmetic). 100 | */ 101 | operator int BenchmarkSuspender::*() const 102 | { 103 | return nullptr; 104 | } 105 | 106 | /** 107 | * Accumulates nanoseconds spent outside benchmark. 108 | */ 109 | typedef uint64_t NanosecondsSpent; 110 | static NanosecondsSpent nsSpent; 111 | 112 | private: 113 | void tally() 114 | { 115 | auto end = getNowTickCount(); 116 | nsSpent += (end - start_); 117 | start_ = end; 118 | } 119 | 120 | uint64_t start_; 121 | }; 122 | 123 | /** 124 | * Adds a benchmark. Usually not called directly but instead through 125 | * the macro BENCHMARK defined below. The lambda function involved 126 | * must take exactly one parameter of type unsigned, and the benchmark 127 | * uses it with counter semantics (iteration occurs inside the 128 | * function). 129 | */ 130 | template 131 | void addBenchmarkWithTimes(const char* file, const char* name, Lambda&& lambda) 132 | { 133 | auto execute = [=](unsigned int times) 134 | { 135 | BenchmarkSuspender::nsSpent = 0; 136 | unsigned int niter; 137 | 138 | // CORE MEASUREMENT STARTS 139 | auto const start = getNowTickCount(); 140 | niter = lambda(times); 141 | auto const end = getNowTickCount(); 142 | // CORE MEASUREMENT ENDS 143 | 144 | return detail::TimeIterPair(end - start - BenchmarkSuspender::nsSpent, niter); 145 | }; 146 | 147 | detail::addBenchmarkImpl(file, name, 148 | std::function(execute)); 149 | } 150 | 151 | template 152 | void addBenchmark(const char* file, const char* name, Lambda&& lambda) 153 | { 154 | addBenchmarkWithTimes(file, name, [=](unsigned int times) 155 | { 156 | unsigned int niter = 0; 157 | while (times-- > 0) { 158 | niter += lambda(times); 159 | } 160 | return niter; 161 | }); 162 | } 163 | 164 | /** 165 | * Call doNotOptimizeAway(var) to ensure that var will be computed even 166 | * post-optimization. Use it for variables that are computed during 167 | * benchmarking but otherwise are useless. The compiler tends to do a 168 | * good job at eliminating unused variables, and this function fools it 169 | * into thinking var is in fact needed. 170 | * 171 | * Call makeUnpredictable(var) when you don't want the optimizer to use 172 | * its knowledge of var to shape the following code. This is useful 173 | * when constant propagation or power reduction is possible during your 174 | * benchmark but not in real use cases. 175 | */ 176 | 177 | #ifdef _MSC_VER 178 | 179 | #pragma optimize("", off) 180 | 181 | inline void doNotOptimizeDependencySink(const void*) {} 182 | 183 | #pragma optimize("", on) 184 | 185 | template 186 | void doNotOptimizeAway(const T& datum) { 187 | doNotOptimizeDependencySink(&datum); 188 | } 189 | 190 | template 191 | void makeUnpredictable(T& datum) { 192 | doNotOptimizeDependencySink(&datum); 193 | } 194 | 195 | #else 196 | 197 | namespace detail { 198 | template 199 | struct DoNotOptimizeAwayNeedsIndirect { 200 | using Decayed = typename std::decay::type; 201 | 202 | // First two constraints ensure it can be an "r" operand. 203 | // std::is_pointer check is because callers seem to expect that 204 | // doNotOptimizeAway(&x) is equivalent to doNotOptimizeAway(x). 205 | const static bool value = sizeof(Decayed) > sizeof(long) || std::is_pointer::value; 206 | }; 207 | } // detail namespace 208 | 209 | template 210 | auto doNotOptimizeAway(const T& datum) -> typename std::enable_if< 211 | !detail::DoNotOptimizeAwayNeedsIndirect::value>::type { 212 | // The "r" constraint forces the compiler to make datum available 213 | // in a register to the asm block, which means that it must have 214 | // computed/loaded it. We use this path for things that are <= 215 | // sizeof(long) (they have to fit), trivial (otherwise the compiler 216 | // doesn't want to put them in a register), and not a pointer (because 217 | // doNotOptimizeAway(&foo) would otherwise be a foot gun that didn't 218 | // necessarily compute foo). 219 | // 220 | // An earlier version of this method had a more permissive input operand 221 | // constraint, but that caused unnecessary variation between clang and 222 | // gcc benchmarks. 223 | asm volatile("" ::"r"(datum)); 224 | } 225 | 226 | template 227 | auto doNotOptimizeAway(const T& datum) -> typename std::enable_if< 228 | detail::DoNotOptimizeAwayNeedsIndirect::value>::type { 229 | // This version of doNotOptimizeAway tells the compiler that the asm 230 | // block will read datum from memory, and that in addition it might read 231 | // or write from any memory location. If the memory clobber could be 232 | // separated into input and output that would be preferrable. 233 | asm volatile("" ::"m"(datum) : "memory"); 234 | } 235 | 236 | template 237 | auto makeUnpredictable(T& datum) -> typename std::enable_if< 238 | !detail::DoNotOptimizeAwayNeedsIndirect::value>::type { 239 | asm volatile("" : "+r"(datum)); 240 | } 241 | 242 | template 243 | auto makeUnpredictable(T& datum) -> typename std::enable_if< 244 | detail::DoNotOptimizeAwayNeedsIndirect::value>::type { 245 | asm volatile("" ::"m"(datum) : "memory"); 246 | } 247 | 248 | #endif 249 | 250 | 251 | 252 | 253 | /** 254 | * Introduces a benchmark function. Used internally, see BENCHMARK and 255 | * friends below. 256 | */ 257 | #define BENCHMARK_IMPL(funName, stringName, paramType, paramName) \ 258 | static void funName(paramType); \ 259 | static bool FB_ANONYMOUS_VARIABLE(follyBenchmarkUnused) = ( \ 260 | addBenchmark(__FILE__, stringName, \ 261 | [](paramType paramName) -> unsigned { funName(paramName); \ 262 | return 1; }), true); \ 263 | static void funName(paramType paramName) 264 | 265 | /** 266 | * Introduces a benchmark function with support for returning the actual 267 | * number of iterations. Used internally, see BENCHMARK_MULTI and friends 268 | * below. 269 | */ 270 | #define BENCHMARK_MULTI_IMPL(funName, stringName, paramType, paramName) \ 271 | static unsigned funName(paramType); \ 272 | static bool FB_ANONYMOUS_VARIABLE(follyBenchmarkUnused) = ( \ 273 | addBenchmark(__FILE__, stringName, \ 274 | [](paramType paramName) { return funName(paramName); }), \ 275 | true); \ 276 | static unsigned funName(paramType paramName) 277 | 278 | /** 279 | * Introduces a benchmark function. Use with two arguments. The first 280 | * is the name of the benchmark. Use something descriptive, such as 281 | * insertVectorBegin. The second argument may be missing, or could be 282 | * a symbolic counter. The counter dictates how many internal iteration 283 | * the benchmark does. Example: 284 | * 285 | * BENCHMARK(insertVectorBegin, n) { 286 | * vector v; 287 | * for(auto i = 0; i < n; i++) { 288 | * v.insert(v.begin(), 42); 289 | * } 290 | * } 291 | */ 292 | #define BENCHMARK(name, n) \ 293 | BENCHMARK_IMPL( \ 294 | name, \ 295 | FB_STRINGIZE(name), \ 296 | unsigned, \ 297 | n) 298 | 299 | /** 300 | * Draws a line of dashes. 301 | */ 302 | #define BENCHMARK_DRAW_LINE() \ 303 | static bool FB_ANONYMOUS_VARIABLE(follyBenchmarkUnused) = ( \ 304 | addBenchmark(__FILE__, "-", \ 305 | [](unsigned) -> unsigned { return 0; }), \ 306 | true); 307 | 308 | /** 309 | * Draws a line of dashes. 310 | */ 311 | #define BENCHMARK_INITIALIZER(funName) \ 312 | static void funName(); \ 313 | static bool FB_ANONYMOUS_VARIABLE(follyBenchmarkUnused) = ( \ 314 | detail::addBenchmarkInit(funName), true); \ 315 | static void funName() 316 | 317 | /** 318 | * Allows execution of code that doesn't count torward the benchmark's 319 | * time budget. Example: 320 | * 321 | * BENCHMARK_START_GROUP(insertVectorBegin, n) { 322 | * vector v; 323 | * BENCHMARK_SUSPEND { 324 | * v.reserve(n); 325 | * } 326 | * for(auto i = 0; i < n; i++) { 327 | * v.insert(v.begin(), 42); 328 | * } 329 | * } 330 | */ 331 | #define BENCHMARK_SUSPEND \ 332 | if (auto FB_ANONYMOUS_VARIABLE(BENCHMARK_SUSPEND) = \ 333 | BenchmarkSuspender()) {} \ 334 | else 335 | 336 | 337 | /** 338 | * Just like BENCHMARK, but prints the time relative to a 339 | * baseline. The baseline is the most recent BENCHMARK() seen in 340 | * lexical order. Example: 341 | * 342 | * // This is the baseline 343 | * BENCHMARK(insertVectorBegin, n) { 344 | * vector v; 345 | * for(auto i = 0; i < n; i++) { 346 | * v.insert(v.begin(), 42); 347 | * } 348 | * } 349 | * 350 | * BENCHMARK_RELATIVE(insertListBegin, n) { 351 | * list s; 352 | * for(auto i = 0; i < n; i++) { 353 | * s.insert(s.begin(), 42); 354 | * } 355 | * } 356 | * 357 | * Any number of relative benchmark can be associated with a 358 | * baseline. Another BENCHMARK() occurrence effectively establishes a 359 | * new baseline. 360 | */ 361 | #define BENCHMARK_RELATIVE(name, n) \ 362 | BENCHMARK_IMPL( \ 363 | name, \ 364 | "%" FB_STRINGIZE(name), \ 365 | unsigned, \ 366 | n) 367 | -------------------------------------------------------------------------------- /src/CmdLineFlags.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008, Google Inc. 2 | // All rights reserved. 3 | 4 | // --- 5 | // This file is a compatibility layer that defines Google's version of 6 | // command line flags that are used for configuration. 7 | // 8 | // We put flags into their own namespace. It is purposefully 9 | // named in an opaque way that people should have trouble typing 10 | // directly. The idea is that DEFINE puts the flag in the weird 11 | // namespace, and DECLARE imports the flag from there into the 12 | // current namespace. The net result is to force people to use 13 | // DECLARE to get access to a flag, rather than saying 14 | // extern bool FLAGS_logtostderr; 15 | // or some such instead. We want this so we can put extra 16 | // functionality (like sanity-checking) in DECLARE if we want, 17 | // and make sure it is picked up everywhere. 18 | // 19 | // We also put the type of the variable in the namespace, so that 20 | // people can't DECLARE_int32 something that they DEFINE_bool'd 21 | // elsewhere. 22 | 23 | #pragma once 24 | 25 | #include 26 | #include 27 | #include 28 | 29 | #define DECLARE_VARIABLE(type, shorttype, name, tn) \ 30 | namespace fL##shorttype { \ 31 | extern type FLAGS_##name; \ 32 | } \ 33 | using fL##shorttype::FLAGS_##name 34 | 35 | #define DEFINE_VARIABLE(type, shorttype, name, value, meaning, tn) \ 36 | namespace fL##shorttype { \ 37 | type FLAGS_##name(value); \ 38 | char FLAGS_no##name; \ 39 | } \ 40 | using fL##shorttype::FLAGS_##name 41 | 42 | // bool specialization 43 | #define DECLARE_bool(name) DECLARE_VARIABLE(bool, B, name, bool) 44 | #define DEFINE_bool(name, val, txt) DEFINE_VARIABLE(bool, B, name, val, txt, bool) 45 | 46 | 47 | #define DECLARE_int32(name) DECLARE_VARIABLE(int32_t, I, name, int32_t) 48 | #define DEFINE_int32(name,val,txt) DEFINE_VARIABLE(int32_t, I, name, val, txt, int32_t) 49 | 50 | #define DECLARE_int64(name) DECLARE_VARIABLE(int64_t, I64, name, int64_t) 51 | #define DEFINE_int64(name,val,txt) DEFINE_VARIABLE(int64_t, I64, name, val, txt, int64_t) 52 | 53 | #define DECLARE_double(name) DECLARE_VARIABLE(double, D, name, double) 54 | #define DEFINE_double(name,val,txt) DEFINE_VARIABLE(double, D, name, val, txt, double) 55 | 56 | // Special case for string, because we have to specify the namespace 57 | // std::string, which doesn't play nicely with our FLAG__namespace hackery. 58 | #define DECLARE_string(name) \ 59 | namespace fLS { \ 60 | extern std::string& FLAGS_##name; \ 61 | } \ 62 | using fLS::FLAGS_##name 63 | 64 | #define DEFINE_string(name, value, meaning) \ 65 | namespace fLS { \ 66 | std::string FLAGS_##name##_buf(value); \ 67 | std::string& FLAGS_##name = FLAGS_##name##_buf; \ 68 | char FLAGS_no##name; \ 69 | } \ 70 | using fLS::FLAGS_##name 71 | 72 | 73 | // If both an environment variable and a flag are specified, the value 74 | // specified by a flag wins. 75 | 76 | #define QSF_DEFINE_bool(name, value, meaning) \ 77 | DEFINE_bool(name, EnvToBool("QSF_" #name, value), meaning) 78 | 79 | #define QSF_DEFINE_int32(name, value, meaning) \ 80 | DEFINE_int32(name, EnvToInt("QSF_" #name, value), meaning) 81 | 82 | #define QSF_DEFINE_string(name, value, meaning) \ 83 | DEFINE_string(name, EnvToString("QSF_" #name, value), meaning) 84 | 85 | // These macros (could be functions, but I don't want to bother with a .cc 86 | // file), make it easier to initialize flags from the environment. 87 | 88 | #define EnvToString(envname, dflt) \ 89 | (!getenv(envname) ? (dflt) : getenv(envname)) 90 | 91 | #define EnvToBool(envname, dflt) \ 92 | (!getenv(envname) ? (dflt) : memchr("tTyY1\0", getenv(envname)[0], 6) != NULL) 93 | 94 | #define EnvToInt(envname, dflt) \ 95 | (!getenv(envname) ? (dflt) : strtol(getenv(envname), NULL, 10)) 96 | -------------------------------------------------------------------------------- /src/Logging.cpp: -------------------------------------------------------------------------------- 1 | // Protocol Buffers - Google's data interchange format 2 | // Copyright 2008 Google Inc. All rights reserved. 3 | // https://developers.google.com/protocol-buffers/ 4 | // 5 | // Redistribution and use in source and binary forms, with or without 6 | // modification, are permitted provided that the following conditions are 7 | // met: 8 | // 9 | // * Redistributions of source code must retain the above copyright 10 | // notice, this list of conditions and the following disclaimer. 11 | // * Redistributions in binary form must reproduce the above 12 | // copyright notice, this list of conditions and the following disclaimer 13 | // in the documentation and/or other materials provided with the 14 | // distribution. 15 | // * Neither the name of Google Inc. nor the names of its 16 | // contributors may be used to endorse or promote products derived from 17 | // this software without specific prior written permission. 18 | // 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 20 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 21 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 22 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 23 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 25 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | 31 | #include "Logging.h" 32 | #include 33 | #include 34 | #include 35 | #include "Preprocessor.h" 36 | 37 | #ifdef _WIN32 38 | #include 39 | #endif 40 | 41 | using std::mutex; 42 | using std::lock_guard; 43 | 44 | namespace internal { 45 | 46 | void DefaultLogHandler(LogLevel level, const char* filename, int line, 47 | const std::string& message) 48 | { 49 | static const char* level_names[] = { "INFO", "WARNING", "ERROR", "FATAL" }; 50 | const char* sep = strrchr(filename, '\\'); 51 | if (sep) 52 | { 53 | filename = sep; 54 | } 55 | char buffer[1024] = {}; 56 | snprintf(buffer, 1023, "[%s %s:%d] %s\n", level_names[level], filename, 57 | line, message.c_str()); 58 | #if defined(_WIN32) 59 | OutputDebugStringA(buffer); 60 | #else 61 | fprintf(stderr, "%s", buffer); 62 | #endif 63 | } 64 | 65 | void NullLogHandler(LogLevel /* level */, const char* /* filename */, 66 | int /* line */, const std::string& /* message */) 67 | { 68 | // Nothing. 69 | } 70 | 71 | static LogHandler* log_handler_ = &DefaultLogHandler; 72 | static int log_silencer_count_ = 0; 73 | static mutex log_silencer_count_mutex_; 74 | 75 | void LogMessage::Finish() { 76 | bool suppress = false; 77 | 78 | if (level_ != LOGLEVEL_FATAL) { 79 | lock_guard lock(log_silencer_count_mutex_); 80 | suppress = log_silencer_count_ > 0; 81 | } 82 | 83 | if (!suppress) { 84 | log_handler_(level_, filename_, line_, message_); 85 | } 86 | 87 | if (level_ == LOGLEVEL_FATAL) { 88 | abort(); 89 | } 90 | } 91 | 92 | void LogFinisher::operator=(LogMessage& other) { 93 | other.Finish(); 94 | } 95 | 96 | } // namespace internal 97 | 98 | 99 | LogHandler* SetLogHandler(LogHandler* new_func) { 100 | LogHandler* old = internal::log_handler_; 101 | if (old == &internal::NullLogHandler) { 102 | old = NULL; 103 | } 104 | if (new_func == NULL) { 105 | internal::log_handler_ = &internal::NullLogHandler; 106 | } 107 | else { 108 | internal::log_handler_ = new_func; 109 | } 110 | return old; 111 | } 112 | -------------------------------------------------------------------------------- /src/Logging.h: -------------------------------------------------------------------------------- 1 | // Protocol Buffers - Google's data interchange format 2 | // Copyright 2008 Google Inc. All rights reserved. 3 | // https://developers.google.com/protocol-buffers/ 4 | // 5 | // Redistribution and use in source and binary forms, with or without 6 | // modification, are permitted provided that the following conditions are 7 | // met: 8 | // 9 | // * Redistributions of source code must retain the above copyright 10 | // notice, this list of conditions and the following disclaimer. 11 | // * Redistributions in binary form must reproduce the above 12 | // copyright notice, this list of conditions and the following disclaimer 13 | // in the documentation and/or other materials provided with the 14 | // distribution. 15 | // * Neither the name of Google Inc. nor the names of its 16 | // contributors may be used to endorse or promote products derived from 17 | // this software without specific prior written permission. 18 | // 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 20 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 21 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 22 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 23 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 25 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | 31 | #ifndef UTILITY_LOGGING_H 32 | #define UTILITY_LOGGING_H 33 | 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | // =================================================================== 40 | // emulates google3/base/logging.h 41 | 42 | enum LogLevel { 43 | LOGLEVEL_INFO, // Informational. 44 | LOGLEVEL_WARNING, // Warns about issues that, although not technically a 45 | // problem now, could cause problems in the future. For 46 | // example, a // warning will be printed when parsing a 47 | // message that is near the message size limit. 48 | LOGLEVEL_ERROR, // An error occurred which should never happen during 49 | // normal use. 50 | LOGLEVEL_FATAL, // An error occurred from which the library cannot 51 | // recover. This usually indicates a programming error 52 | // in the code which calls the library, especially when 53 | // compiled in debug mode. 54 | 55 | LOGLEVEL_DFATAL = LOGLEVEL_FATAL 56 | }; 57 | 58 | namespace internal { 59 | 60 | class LogFinisher; 61 | 62 | class LogMessage { 63 | public: 64 | LogMessage(LogLevel level, const char* filename, int line) 65 | : level_(level), filename_(filename), line_(line) 66 | { 67 | } 68 | 69 | ~LogMessage() 70 | { 71 | } 72 | 73 | LogMessage& operator<<(const std::string& value) 74 | { 75 | message_ += value; 76 | return *this; 77 | } 78 | 79 | LogMessage& operator<<(const char* value) 80 | { 81 | message_ += value; 82 | return *this; 83 | } 84 | 85 | template 86 | typename std::enable_if< 87 | std::is_arithmetic::value 88 | || std::is_enum::value, LogMessage&>::type 89 | operator<<(T value) 90 | { 91 | std::ostringstream os; 92 | os << value; 93 | message_ += os.str(); 94 | return *this; 95 | } 96 | 97 | private: 98 | friend class LogFinisher; 99 | void Finish(); 100 | 101 | LogLevel level_; 102 | const char* filename_; 103 | int line_; 104 | std::string message_; 105 | }; 106 | 107 | // Used to make the entire "LOG(BLAH) << etc." expression have a void return 108 | // type and print a newline after each message. 109 | class LogFinisher { 110 | public: 111 | void operator=(LogMessage& other); 112 | }; 113 | 114 | } // namespace internal 115 | 116 | // Undef everything in case we're being mixed with some other Google library 117 | // which already defined them itself. Presumably all Google libraries will 118 | // support the same syntax for these so it should not be a big deal if they 119 | // end up using our definitions instead. 120 | #undef LOG 121 | #undef LOG_IF 122 | 123 | #undef CHECK 124 | #undef CHECK_OK 125 | #undef CHECK_EQ 126 | #undef CHECK_NE 127 | #undef CHECK_LT 128 | #undef CHECK_LE 129 | #undef CHECK_GT 130 | #undef CHECK_GE 131 | #undef CHECK_NOTNULL 132 | 133 | #undef DLOG 134 | #undef DCHECK 135 | #undef DCHECK_EQ 136 | #undef DCHECK_NE 137 | #undef DCHECK_LT 138 | #undef DCHECK_LE 139 | #undef DCHECK_GT 140 | #undef DCHECK_GE 141 | 142 | #define LOG(LEVEL) \ 143 | ::internal::LogFinisher() = \ 144 | ::internal::LogMessage(::LOGLEVEL_##LEVEL, __FILE__, __LINE__) 145 | 146 | #define LOG_IF(LEVEL, CONDITION) \ 147 | !(CONDITION) ? (void)0 : LOG(LEVEL) 148 | 149 | #define CHECK(EXPRESSION) \ 150 | LOG_IF(FATAL, !(EXPRESSION)) << "CHECK failed: " #EXPRESSION ": " 151 | #define CHECK_OK(A) CHECK(A) 152 | #define CHECK_EQ(A, B) CHECK((A) == (B)) 153 | #define CHECK_NE(A, B) CHECK((A) != (B)) 154 | #define CHECK_LT(A, B) CHECK((A) < (B)) 155 | #define CHECK_LE(A, B) CHECK((A) <= (B)) 156 | #define CHECK_GT(A, B) CHECK((A) > (B)) 157 | #define CHECK_GE(A, B) CHECK((A) >= (B)) 158 | 159 | 160 | namespace internal { 161 | template 162 | T* CheckNotNull(const char* /* file */, int /* line */, 163 | const char* name, T* val) { 164 | if (val == NULL) { 165 | LOG(FATAL) << name; 166 | } 167 | return val; 168 | } 169 | } // namespace internal 170 | 171 | 172 | #define CHECK_NOTNULL(A) \ 173 | ::internal::CheckNotNull(__FILE__, __LINE__, "'" #A "' must not be NULL", (A)) 174 | 175 | #ifdef NDEBUG 176 | 177 | #define DLOG LOG_IF(INFO, false) 178 | 179 | #define DCHECK(EXPRESSION) while(false) CHECK(EXPRESSION) 180 | #define DCHECK_EQ(A, B) DCHECK((A) == (B)) 181 | #define DCHECK_NE(A, B) DCHECK((A) != (B)) 182 | #define DCHECK_LT(A, B) DCHECK((A) < (B)) 183 | #define DCHECK_LE(A, B) DCHECK((A) <= (B)) 184 | #define DCHECK_GT(A, B) DCHECK((A) > (B)) 185 | #define DCHECK_GE(A, B) DCHECK((A) >= (B)) 186 | #define DCHECK_NOTNULL CHECK_NOTNULL 187 | 188 | #else // NDEBUG 189 | 190 | #define DLOG LOG 191 | 192 | #define DCHECK CHECK 193 | #define DCHECK_EQ CHECK_EQ 194 | #define DCHECK_NE CHECK_NE 195 | #define DCHECK_LT CHECK_LT 196 | #define DCHECK_LE CHECK_LE 197 | #define DCHECK_GT CHECK_GT 198 | #define DCHECK_GE CHECK_GE 199 | #define DCHECK_NOTNULL CHECK_NOTNULL 200 | 201 | #endif // !NDEBUG 202 | 203 | typedef void LogHandler(LogLevel level, const char* filename, int line, 204 | const std::string& message); 205 | 206 | // The protobuf library sometimes writes warning and error messages to 207 | // stderr. These messages are primarily useful for developers, but may 208 | // also help end users figure out a problem. If you would prefer that 209 | // these messages be sent somewhere other than stderr, call SetLogHandler() 210 | // to set your own handler. This returns the old handler. Set the handler 211 | // to NULL to ignore log messages (but see also LogSilencer, below). 212 | // 213 | // Obviously, SetLogHandler is not thread-safe. You should only call it 214 | // at initialization time, and probably not from library code. If you 215 | // simply want to suppress log messages temporarily (e.g. because you 216 | // have some code that tends to trigger them frequently and you know 217 | // the warnings are not important to you), use the LogSilencer class 218 | // below. 219 | LogHandler* SetLogHandler(LogHandler* new_func); 220 | 221 | 222 | #endif // UTILITY_LOGGING_H -------------------------------------------------------------------------------- /src/Preprocessor.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Facebook, Inc. 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 | // @author: Andrei Alexandrescu 18 | 19 | #pragma once 20 | 21 | /** 22 | * FB_ANONYMOUS_VARIABLE(str) introduces an identifier starting with 23 | * str and ending with a number that varies with the line. 24 | */ 25 | #ifndef FB_ANONYMOUS_VARIABLE 26 | #define FB_CONCATENATE_IMPL(s1, s2) s1##s2 27 | #define FB_CONCATENATE(s1, s2) FB_CONCATENATE_IMPL(s1, s2) 28 | #ifdef __COUNTER__ 29 | #define FB_ANONYMOUS_VARIABLE(str) FB_CONCATENATE(str, __COUNTER__) 30 | #else 31 | #define FB_ANONYMOUS_VARIABLE(str) FB_CONCATENATE(str, __LINE__) 32 | #endif 33 | #endif 34 | 35 | /** 36 | * Use FB_STRINGIZE(x) when you'd want to do what #x does inside 37 | * another macro expansion. 38 | */ 39 | #define FB_STRINGIZE(x) #x 40 | 41 | #ifdef _MSC_VER 42 | #define snprintf sprintf_s 43 | #endif -------------------------------------------------------------------------------- /test/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2014-present prototyped.cn All rights reserved. 2 | # Distributed under the terms and conditions of the Apache License. 3 | # See accompanying files LICENSE. 4 | 5 | project (BenchTest) 6 | 7 | 8 | file(GLOB BENCH_HEADER_FILES *.h) 9 | file(GLOB BENCH_SOURCE_FILES *.cpp) 10 | 11 | 12 | if (WIN32) 13 | set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:CONSOLE") 14 | add_executable(BenchTest WIN32 ${BENCH_HEADER_FILES} ${BENCH_SOURCE_FILES}) 15 | elseif(UNIX) 16 | add_executable(BenchTest ${BENCH_HEADER_FILES} ${BENCH_SOURCE_FILES}) 17 | target_link_libraries(BenchTest rt) 18 | endif() 19 | 20 | target_link_libraries(BenchTest libbench) 21 | -------------------------------------------------------------------------------- /test/hashmap_bench.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2014-present prototyped.cn All rights reserved. 2 | // Distributed under the terms and conditions of the Apache License. 3 | // See accompanying files LICENSE. 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "Benchmark.h" 10 | 11 | template 12 | T& createIntKeyMap(T& dict, int n) 13 | { 14 | for (int i = 0; i < n; i++) 15 | { 16 | dict[i] = i * i; 17 | } 18 | return dict; 19 | } 20 | 21 | void createIntIndex(std::vector& vec, int n) 22 | { 23 | vec.resize(n); 24 | for (int i = 0; i < n; i++) 25 | { 26 | vec[i] = i; 27 | } 28 | random_shuffle(vec.begin(), vec.end()); 29 | } 30 | 31 | // random insert 32 | BENCHMARK(TreeMapInsert, n) 33 | { 34 | std::map dict; 35 | std::vector index; 36 | BENCHMARK_SUSPEND 37 | { 38 | createIntIndex(index, n); 39 | } 40 | for (unsigned i = 0; i < n; i++) 41 | { 42 | dict[index[i]] = i; 43 | } 44 | doNotOptimizeAway(dict); 45 | } 46 | 47 | BENCHMARK_RELATIVE(HashMapInsert, n) 48 | { 49 | std::unordered_map dict; 50 | std::vector index; 51 | BENCHMARK_SUSPEND 52 | { 53 | createIntIndex(index, n); 54 | } 55 | for (unsigned i = 0; i < n; i++) 56 | { 57 | dict[index[i]] = i; 58 | } 59 | doNotOptimizeAway(dict); 60 | } 61 | 62 | // random delete 63 | BENCHMARK(TreeMapDelete, n) 64 | { 65 | std::map dict; 66 | std::vector index; 67 | BENCHMARK_SUSPEND 68 | { 69 | createIntKeyMap(dict, n); 70 | createIntIndex(index, n); 71 | } 72 | for (unsigned i = 0; i < n; i++) 73 | { 74 | dict.erase(index[i]); 75 | } 76 | doNotOptimizeAway(dict); 77 | } 78 | 79 | BENCHMARK_RELATIVE(HashMapDelete, n) 80 | { 81 | std::unordered_map dict; 82 | std::vector index; 83 | BENCHMARK_SUSPEND 84 | { 85 | createIntKeyMap(dict, n); 86 | createIntIndex(index, n); 87 | } 88 | for (unsigned i = 0; i < n; i++) 89 | { 90 | dict.erase(index[i]); 91 | } 92 | doNotOptimizeAway(dict); 93 | } 94 | 95 | // random find 96 | BENCHMARK(TreeMapIntFind, n) 97 | { 98 | std::map dict; 99 | std::vector index; 100 | BENCHMARK_SUSPEND 101 | { 102 | createIntKeyMap(dict, n); 103 | createIntIndex(index, n); 104 | } 105 | int64_t total = 0; 106 | for (unsigned i = 0; i < n; i++) 107 | { 108 | auto iter = dict.find(index[i]); 109 | if (iter != dict.end()) 110 | { 111 | total += iter->second; 112 | } 113 | } 114 | doNotOptimizeAway(dict); 115 | doNotOptimizeAway(total); 116 | } 117 | 118 | BENCHMARK_RELATIVE(HashMapIntFind, n) 119 | { 120 | std::unordered_map dict; 121 | std::vector index; 122 | BENCHMARK_SUSPEND 123 | { 124 | createIntKeyMap(dict, n); 125 | createIntIndex(index, n); 126 | } 127 | int64_t total = 0; 128 | for (unsigned i = 0; i < n; i++) 129 | { 130 | auto iter = dict.find(index[i]); 131 | if (iter != dict.end()) 132 | { 133 | total += iter->second; 134 | } 135 | } 136 | doNotOptimizeAway(dict); 137 | doNotOptimizeAway(total); 138 | } 139 | -------------------------------------------------------------------------------- /test/main.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2014-present prototyped.cn All rights reserved. 2 | // Distributed under the terms and conditions of the Apache License. 3 | // See accompanying files LICENSE. 4 | 5 | #include 6 | #include "Benchmark.h" 7 | #include 8 | #include 9 | 10 | using std::cout; 11 | using std::endl; 12 | 13 | 14 | int main(int argc, char* argv[]) 15 | { 16 | srand((int)time(NULL)); 17 | cout << "\nPATIENCE, BENCHMARKS IN PROGRESS." << endl; 18 | runBenchmarks(); 19 | cout << "MEASUREMENTS DONE." << endl; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /test/map_find_bench.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2014-present prototyped.cn All rights reserved. 2 | // Distributed under the terms and conditions of the Apache License. 3 | // See accompanying files LICENSE. 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "Benchmark.h" 11 | 12 | const std::string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 13 | const int MAX_KEY_LEN = 64; 14 | 15 | std::string randAlphabetString(int length) 16 | { 17 | std::string text; 18 | text.resize(length); 19 | for (int i = 0; i < length; i++) 20 | { 21 | int idx = rand() % alphabet.size(); 22 | text[i] = alphabet[idx]; 23 | } 24 | return std::move(text); 25 | } 26 | 27 | template 28 | T& createStringKeyMap(const std::vector& vec, T& dict) 29 | { 30 | for (auto i = 0U; i < vec.size(); i++) 31 | { 32 | dict[vec[i]] = i * i; 33 | } 34 | return dict; 35 | } 36 | 37 | void createStringIndex(std::vector& vec, int n) 38 | { 39 | vec.resize(n); 40 | for (int i = 0; i < n; i++) 41 | { 42 | vec[i] = randAlphabetString(rand() % MAX_KEY_LEN); 43 | } 44 | } 45 | 46 | 47 | // random find 48 | BENCHMARK(TreeMapStringFind, n) 49 | { 50 | std::map dict; 51 | std::vector index; 52 | BENCHMARK_SUSPEND 53 | { 54 | createStringIndex(index, n); 55 | createStringKeyMap(index, dict); 56 | std::random_shuffle(index.begin(), index.end()); 57 | } 58 | int64_t total = 0; 59 | for (unsigned i = 0; i < n; i++) 60 | { 61 | auto iter = dict.find(index[i]); 62 | if (iter != dict.end()) 63 | { 64 | total += iter->second; 65 | } 66 | } 67 | doNotOptimizeAway(dict); 68 | doNotOptimizeAway(total); 69 | } 70 | 71 | BENCHMARK_RELATIVE(HashMapStringFind, n) 72 | { 73 | std::unordered_map dict; 74 | std::vector index; 75 | BENCHMARK_SUSPEND 76 | { 77 | createStringIndex(index, n); 78 | createStringKeyMap(index, dict); 79 | std::random_shuffle(index.begin(), index.end()); 80 | } 81 | int64_t total = 0; 82 | for (unsigned i = 0; i < n; i++) 83 | { 84 | auto iter = dict.find(index[i]); 85 | if (iter != dict.end()) 86 | { 87 | total += iter->second; 88 | } 89 | } 90 | doNotOptimizeAway(dict); 91 | doNotOptimizeAway(total); 92 | } -------------------------------------------------------------------------------- /test/small_map_find_bench.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2014-present prototyped.cn All rights reserved. 2 | // Distributed under the terms and conditions of the Apache License. 3 | // See accompanying files LICENSE. 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "Benchmark.h" 10 | 11 | struct Point { 12 | int16_t x = 0; 13 | int16_t y = 0; 14 | }; 15 | 16 | const int SMALL_FIND_VALUE = 100; 17 | 18 | template 19 | static T& getSmallMap(int n) 20 | { 21 | static T dict; 22 | if (!dict.empty()) 23 | { 24 | return dict; 25 | } 26 | for (int i = 1; i <= n; i++) 27 | { 28 | Point pt; 29 | pt.x = rand() % 0xFFFF; 30 | pt.y = rand() % 0xFFFF; 31 | int32_t cell = (pt.x << 16) | pt.y; 32 | dict[cell] = pt; 33 | } 34 | return dict; 35 | } 36 | 37 | template 38 | static T& getSmallPtrMap(int n) 39 | { 40 | static T dict; 41 | if (!dict.empty()) 42 | { 43 | return dict; 44 | } 45 | for (int i = 1; i <= n; i++) 46 | { 47 | auto pt = new Point; 48 | pt->x = rand() % 0xFFFF; 49 | pt->y = rand() % 0xFFFF; 50 | int32_t cell = (pt->x << 16) | pt->y; 51 | dict[cell] = pt; 52 | } 53 | return dict; 54 | } 55 | 56 | static std::vector& getSmallVector(int n) 57 | { 58 | static std::vector vec; 59 | if (!vec.empty()) 60 | { 61 | return vec; 62 | } 63 | for (int i = 1; i <= n; i++) 64 | { 65 | Point pt; 66 | pt.x = rand() % 0xFFFF; 67 | pt.y = rand() % 0xFFFF; 68 | vec.push_back(pt); 69 | } 70 | return vec; 71 | } 72 | 73 | static std::vector& getSmallPtrVector(int n) 74 | { 75 | static std::vector vec; 76 | if (!vec.empty()) 77 | { 78 | return vec; 79 | } 80 | for (int i = 1; i <= n; i++) 81 | { 82 | auto pt = new Point; 83 | pt->x = rand() % 0xFFFF; 84 | pt->y = rand() % 0xFFFF; 85 | vec.push_back(pt); 86 | } 87 | return vec; 88 | } 89 | 90 | static bool smallVectorFind(const std::vector& vec, int32_t cell) 91 | { 92 | for (auto i = 0U; i < vec.size(); i++) 93 | { 94 | int32_t v = vec[i].x + vec[i].y; 95 | if (v == cell) 96 | { 97 | return true; 98 | } 99 | } 100 | return false; 101 | } 102 | 103 | static bool smallPtrVectorFind(const std::vector& vec, int32_t cell) 104 | { 105 | for (auto i = 0U; i < vec.size(); i++) 106 | { 107 | int32_t v = vec[i]->x + vec[i]->y; 108 | if (v == cell) 109 | { 110 | return true; 111 | } 112 | } 113 | return false; 114 | } 115 | 116 | auto small_dict = getSmallMap>(SMALL_FIND_VALUE); 117 | auto small_dict_ptr = getSmallPtrMap>(SMALL_FIND_VALUE); 118 | auto small_vec = getSmallVector(SMALL_FIND_VALUE); 119 | auto small_vec_ptr = getSmallPtrVector(SMALL_FIND_VALUE); 120 | 121 | 122 | BENCHMARK(SmallMapFind, n) 123 | { 124 | const auto& dict = small_dict; 125 | uint64_t sum = 0; 126 | for (unsigned i = 1; i <= n; i++) 127 | { 128 | int32_t cell = rand() % 0xFFFF; 129 | if (dict.count(cell) > 0) 130 | { 131 | sum += i; 132 | } 133 | } 134 | doNotOptimizeAway(sum); 135 | doNotOptimizeAway(dict); 136 | } 137 | 138 | BENCHMARK_RELATIVE(SmallVectorFind, n) 139 | { 140 | const std::vector& vec = small_vec; 141 | uint64_t sum = 0; 142 | for (unsigned i = 1; i <= n; i++) 143 | { 144 | int32_t cell = rand() % 0xFFFF; 145 | if (smallVectorFind(vec, cell)) 146 | { 147 | sum += i; 148 | } 149 | } 150 | doNotOptimizeAway(sum); 151 | doNotOptimizeAway(vec); 152 | } 153 | 154 | BENCHMARK(SmallMapPtrFind, n) 155 | { 156 | auto dict = small_dict_ptr; 157 | uint64_t sum = 0; 158 | for (unsigned i = 1; i <= n; i++) 159 | { 160 | int32_t cell = rand() % 0xFFFF; 161 | if (dict.count(cell) > 0) 162 | { 163 | sum += i; 164 | } 165 | } 166 | doNotOptimizeAway(sum); 167 | doNotOptimizeAway(dict); 168 | } 169 | 170 | BENCHMARK_RELATIVE(SmallVectorPtrFind, n) 171 | { 172 | const std::vector& vec = small_vec_ptr; 173 | uint64_t sum = 0; 174 | for (unsigned i = 1; i <= n; i++) 175 | { 176 | int32_t cell = rand() % 0xFFFF; 177 | if (smallPtrVectorFind(vec, cell)) 178 | { 179 | sum += i; 180 | } 181 | } 182 | doNotOptimizeAway(sum); 183 | doNotOptimizeAway(vec); 184 | } 185 | --------------------------------------------------------------------------------