| 1 | /* |
| 2 | * Open Chinese Convert |
| 3 | * |
| 4 | * Copyright 2020-2026 Carbo Kuo and contributors |
| 5 | * |
| 6 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | * you may not use this file except in compliance with the License. |
| 8 | * You may obtain a copy of the License at |
| 9 | * |
| 10 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | * |
| 12 | * Unless required by applicable law or agreed to in writing, software |
| 13 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | * See the License for the specific language governing permissions and |
| 16 | * limitations under the License. |
| 17 | */ |
| 18 | |
| 19 | #include <benchmark/benchmark.h> |
| 20 | #include <cstdlib> |
| 21 | #include <cstdio> |
| 22 | #include <fstream> |
| 23 | #include <iomanip> |
| 24 | #include <memory> |
| 25 | #include <ostream> |
| 26 | #include <sstream> |
| 27 | #include <streambuf> |
| 28 | #include <string> |
| 29 | #include <vector> |
| 30 | |
| 31 | #ifdef _MSC_VER |
| 32 | #include <direct.h> |
| 33 | #include <process.h> |
| 34 | #else |
| 35 | #include <sys/stat.h> |
| 36 | #include <unistd.h> |
| 37 | #endif |
| 38 | |
| 39 | #include <rapidjson/document.h> |
| 40 | #include <rapidjson/stringbuffer.h> |
| 41 | #include <rapidjson/writer.h> |
| 42 | |
| 43 | #include "Exception.hpp" |
| 44 | #include "SimpleConverter.hpp" |
| 45 | #include "TestUtilsUTF8.hpp" |
| 46 | |
| 47 | namespace opencc { |
| 48 | |
| 49 | namespace { |
| 50 | |
| 51 | using JSONDocument = rapidjson::Document; |
| 52 | using JSONValue = rapidjson::Value; |
| 53 | |
| 54 | struct BenchmarkConfig { |
| 55 | std::string name; |
| 56 | std::string path; |
| 57 | }; |
| 58 | |
| 59 | #ifdef OPENCC_BENCHMARK_JIEBA_CONFIG_DIR |
| 60 | void SetPluginSearchPath(const char* path) { |
| 61 | if (path == nullptr || *path == '\0') { |
| 62 | return; |
| 63 | } |
| 64 | #ifdef _WIN32 |
| 65 | _putenv_s("OPENCC_SEGMENTATION_PLUGIN_PATH", path); |
| 66 | #else |
| 67 | setenv("OPENCC_SEGMENTATION_PLUGIN_PATH", path, 1); |
| 68 | #endif |
| 69 | } |
| 70 | #endif |
| 71 | |
| 72 | bool IsRegularFile(const std::string& path) { |
| 73 | std::ifstream stream(path.c_str(), std::ios::binary); |
| 74 | return stream.good(); |
| 75 | } |
| 76 | |
| 77 | bool EndsWith(const std::string& value, const std::string& suffix) { |
| 78 | return value.size() >= suffix.size() && |
| 79 | value.compare(value.size() - suffix.size(), suffix.size(), suffix) == 0; |
| 80 | } |
| 81 | |
| 82 | std::string ReplaceSuffix(const std::string& value, const std::string& from, |
| 83 | const std::string& to) { |
| 84 | if (!EndsWith(value, from)) { |
| 85 | return value; |
| 86 | } |
| 87 | return value.substr(0, value.size() - from.size()) + to; |
| 88 | } |
| 89 | |
| 90 | std::string GetProcessIdString() { |
| 91 | #ifdef _WIN32 |
| 92 | return std::to_string(_getpid()); |
| 93 | #else |
| 94 | return std::to_string(getpid()); |
| 95 | #endif |
| 96 | } |
| 97 | |
| 98 | std::string GetBaseNameWithoutExtension(const std::string& path) { |
| 99 | const std::string::size_type slash_pos = path.find_last_of("/\\"); |
| 100 | const std::string::size_type start = |
| 101 | slash_pos == std::string::npos ? 0 : slash_pos + 1; |
| 102 | const std::string::size_type dot_pos = path.find_last_of('.'); |
| 103 | if (dot_pos == std::string::npos || dot_pos < start) { |
| 104 | return path.substr(start); |
| 105 | } |
| 106 | return path.substr(start, dot_pos - start); |
| 107 | } |
| 108 | |
| 109 | std::string BenchmarkTempDirectory() { |
| 110 | return std::string(PROJECT_BINARY_DIR) + "/src/benchmark/"; |
| 111 | } |
| 112 | |
| 113 | bool IsAbsolutePath(const std::string& path) { |
| 114 | if (path.empty()) { |
| 115 | return false; |
| 116 | } |
| 117 | #ifdef _WIN32 |
| 118 | return path.size() > 2 && |
| 119 | ((path[0] >= 'A' && path[0] <= 'Z') || |
| 120 | (path[0] >= 'a' && path[0] <= 'z')) && |
| 121 | path[1] == ':' && (path[2] == '/' || path[2] == '\\'); |
| 122 | #else |
| 123 | return path[0] == '/'; |
| 124 | #endif |
| 125 | } |
| 126 | |
| 127 | std::string JoinPath(const std::string& directory, const std::string& child) { |
| 128 | if (directory.empty()) { |
| 129 | return child; |
| 130 | } |
| 131 | const char last = directory[directory.size() - 1]; |
| 132 | if (last == '/' || last == '\\') { |
| 133 | return directory + child; |
| 134 | } |
| 135 | return directory + "/" + child; |
| 136 | } |
| 137 | |
| 138 | std::string GetParentDirectory(const std::string& path) { |
| 139 | const std::string::size_type pos = path.find_last_of("/\\"); |
| 140 | if (pos == std::string::npos) { |
| 141 | return ""; |
| 142 | } |
| 143 | return path.substr(0, pos + 1); |
| 144 | } |
| 145 | |
| 146 | std::string ResolveConfigPath(const std::string& config_name) { |
| 147 | #ifdef OPENCC_BENCHMARK_JIEBA_CONFIG_DIR |
| 148 | if (config_name == "s2twp_jieba") { |
| 149 | SetPluginSearchPath(OPENCC_BENCHMARK_JIEBA_PLUGIN_DIR); |
| 150 | return std::string(OPENCC_BENCHMARK_JIEBA_CONFIG_DIR) + "/" + config_name + |
| 151 | ".json"; |
| 152 | } |
| 153 | #endif |
| 154 | return std::string(PROJECT_SOURCE_DIR) + "/data/config/" + config_name + ".json"; |
| 155 | } |
| 156 | |
| 157 | std::string ResolveTextDictionaryPath(const std::string& dict_file_name) { |
| 158 | const std::string text_file_name = |
| 159 | ReplaceSuffix(dict_file_name, ".ocd2", ".txt"); |
| 160 | const std::string source_path = |
| 161 | std::string(PROJECT_SOURCE_DIR) + "/data/dictionary/" + text_file_name; |
| 162 | if (IsRegularFile(source_path)) { |
| 163 | return source_path; |
| 164 | } |
| 165 | |
| 166 | const std::string generated_path = |
| 167 | std::string(PROJECT_BINARY_DIR) + "/data/" + text_file_name; |
| 168 | if (IsRegularFile(generated_path)) { |
| 169 | return generated_path; |
| 170 | } |
| 171 | |
| 172 | throw FileNotFound(text_file_name); |
| 173 | } |
| 174 | |
| 175 | std::string ResolveSegmentationResourcePath( |
| 176 | const std::string& source_config_directory, const std::string& resource_path) { |
| 177 | if (IsAbsolutePath(resource_path)) { |
| 178 | return resource_path; |
| 179 | } |
| 180 | |
| 181 | #ifdef OPENCC_BENCHMARK_JIEBA_CONFIG_DIR |
| 182 | if (resource_path.find("jieba_dict/") == 0) { |
| 183 | const std::string basename = |
| 184 | resource_path.substr(std::string("jieba_dict/").size()); |
| 185 | const std::string plugin_build_path = |
| 186 | JoinPath(std::string(OPENCC_BENCHMARK_JIEBA_PLUGIN_DIR), resource_path); |
| 187 | if (IsRegularFile(plugin_build_path)) { |
| 188 | return plugin_build_path; |
| 189 | } |
| 190 | const std::string plugin_parent_path = |
| 191 | JoinPath(GetParentDirectory(OPENCC_BENCHMARK_JIEBA_PLUGIN_DIR), resource_path); |
| 192 | if (IsRegularFile(plugin_parent_path)) { |
| 193 | return plugin_parent_path; |
| 194 | } |
| 195 | const std::string source_jieba_path = |
| 196 | std::string(PROJECT_SOURCE_DIR) + "/plugins/jieba/deps/cppjieba/dict/" + |
| 197 | basename; |
| 198 | if (IsRegularFile(source_jieba_path)) { |
| 199 | return source_jieba_path; |
| 200 | } |
| 201 | } |
| 202 | #endif |
| 203 | |
| 204 | return JoinPath(source_config_directory, resource_path); |
| 205 | } |
| 206 | |
| 207 | void RewriteDictNode(JSONValue& node, JSONDocument::AllocatorType& allocator, |
| 208 | const char* target_type) { |
| 209 | if (!node.IsObject()) { |
| 210 | return; |
| 211 | } |
| 212 | |
| 213 | if (node.HasMember("type") && node["type"].IsString() && |
| 214 | std::string(node["type"].GetString()) == "group" && node.HasMember("dicts") && |
| 215 | node["dicts"].IsArray()) { |
| 216 | for (auto& child : node["dicts"].GetArray()) { |
| 217 | RewriteDictNode(child, allocator, target_type); |
| 218 | } |
| 219 | return; |
| 220 | } |
| 221 | |
| 222 | if (!node.HasMember("type") || !node["type"].IsString() || |
| 223 | !node.HasMember("file") || !node["file"].IsString()) { |
| 224 | return; |
| 225 | } |
| 226 | |
| 227 | const std::string type = node["type"].GetString(); |
| 228 | const std::string file_name = node["file"].GetString(); |
| 229 | if (type != "ocd2" || !EndsWith(file_name, ".ocd2")) { |
| 230 | return; |
| 231 | } |
| 232 | |
| 233 | const std::string text_path = ResolveTextDictionaryPath(file_name); |
| 234 | node["type"].SetString(target_type, allocator); |
| 235 | node["file"].SetString(text_path.c_str(), |
| 236 | static_cast<rapidjson::SizeType>(text_path.size()), |
| 237 | allocator); |
| 238 | } |
| 239 | |
| 240 | void RewriteConfigToText(JSONValue& node, JSONDocument::AllocatorType& allocator, |
| 241 | const char* target_type) { |
| 242 | if (node.IsObject()) { |
| 243 | auto type_member = node.FindMember("type"); |
| 244 | auto file_member = node.FindMember("file"); |
| 245 | if (type_member != node.MemberEnd() && file_member != node.MemberEnd()) { |
| 246 | RewriteDictNode(node, allocator, target_type); |
| 247 | } |
| 248 | |
| 249 | for (auto it = node.MemberBegin(); it != node.MemberEnd(); ++it) { |
| 250 | RewriteConfigToText(it->value, allocator, target_type); |
| 251 | } |
| 252 | return; |
| 253 | } |
| 254 | |
| 255 | if (node.IsArray()) { |
| 256 | for (auto& child : node.GetArray()) { |
| 257 | RewriteConfigToText(child, allocator, target_type); |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | void RewriteSegmentationResourcesToAbsolute( |
| 263 | JSONValue& node, JSONDocument::AllocatorType& allocator, |
| 264 | const std::string& source_config_directory) { |
| 265 | if (node.IsObject()) { |
| 266 | auto segmentation_member = node.FindMember("segmentation"); |
| 267 | if (segmentation_member != node.MemberEnd() && |
| 268 | segmentation_member->value.IsObject()) { |
| 269 | auto resources_member = |
| 270 | segmentation_member->value.FindMember("resources"); |
| 271 | if (resources_member != segmentation_member->value.MemberEnd() && |
| 272 | resources_member->value.IsObject()) { |
| 273 | for (auto it = resources_member->value.MemberBegin(); |
| 274 | it != resources_member->value.MemberEnd(); ++it) { |
| 275 | if (!it->value.IsString()) { |
| 276 | continue; |
| 277 | } |
| 278 | const std::string resource_path = it->value.GetString(); |
| 279 | if (IsAbsolutePath(resource_path)) { |
| 280 | continue; |
| 281 | } |
| 282 | const std::string absolute_path = ResolveSegmentationResourcePath( |
| 283 | source_config_directory, resource_path); |
| 284 | it->value.SetString( |
| 285 | absolute_path.c_str(), |
| 286 | static_cast<rapidjson::SizeType>(absolute_path.size()), allocator); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | for (auto it = node.MemberBegin(); it != node.MemberEnd(); ++it) { |
| 292 | RewriteSegmentationResourcesToAbsolute(it->value, allocator, |
| 293 | source_config_directory); |
| 294 | } |
| 295 | return; |
| 296 | } |
| 297 | |
| 298 | if (node.IsArray()) { |
| 299 | for (auto& child : node.GetArray()) { |
| 300 | RewriteSegmentationResourcesToAbsolute(child, allocator, |
| 301 | source_config_directory); |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | std::string ReadFile(const std::string& path) { |
| 307 | std::ifstream stream(path.c_str(), std::ios::binary); |
| 308 | return std::string((std::istreambuf_iterator<char>(stream)), |
| 309 | std::istreambuf_iterator<char>()); |
| 310 | } |
| 311 | |
| 312 | class TemporaryTextConfigRegistry { |
| 313 | public: |
| 314 | ~TemporaryTextConfigRegistry() { |
| 315 | for (const std::string& path : paths_) { |
| 316 | std::remove(path.c_str()); |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | std::string Create(const std::string& source_config_path, |
| 321 | const char* target_type, |
| 322 | const std::string& suffix) { |
| 323 | const std::string content = ReadFile(source_config_path); |
| 324 | JSONDocument document; |
| 325 | document.Parse(content.c_str()); |
| 326 | if (document.HasParseError() || !document.IsObject()) { |
| 327 | throw InvalidFormat("Error parsing benchmark config JSON"); |
| 328 | } |
| 329 | |
| 330 | RewriteConfigToText(document, document.GetAllocator(), target_type); |
| 331 | RewriteSegmentationResourcesToAbsolute(document, document.GetAllocator(), |
| 332 | GetParentDirectory(source_config_path)); |
| 333 | |
| 334 | rapidjson::StringBuffer buffer; |
| 335 | rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); |
| 336 | document.Accept(writer); |
| 337 | |
| 338 | const std::string temp_path = BuildTempPath(source_config_path, suffix); |
| 339 | std::ofstream stream(temp_path.c_str(), std::ios::binary); |
| 340 | stream << buffer.GetString(); |
| 341 | stream.close(); |
| 342 | if (!stream) { |
| 343 | throw FileNotWritable(temp_path); |
| 344 | } |
| 345 | |
| 346 | paths_.push_back(temp_path); |
| 347 | return temp_path; |
| 348 | } |
| 349 | |
| 350 | private: |
| 351 | std::string BuildTempPath(const std::string& source_config_path, |
| 352 | const std::string& suffix) { |
| 353 | const std::string base_name = |
| 354 | GetBaseNameWithoutExtension(source_config_path) + "." + suffix; |
| 355 | const std::string pid = GetProcessIdString(); |
| 356 | std::string path; |
| 357 | do { |
| 358 | path = BenchmarkTempDirectory() + base_name + "." + pid + "." + |
| 359 | std::to_string(counter_++) + ".json"; |
| 360 | } while (IsRegularFile(path)); |
| 361 | return path; |
| 362 | } |
| 363 | |
| 364 | int counter_ = 0; |
| 365 | std::vector<std::string> paths_; |
| 366 | }; |
| 367 | |
| 368 | TemporaryTextConfigRegistry& GetTemporaryTextConfigRegistry() { |
| 369 | static TemporaryTextConfigRegistry registry; |
| 370 | return registry; |
| 371 | } |
| 372 | |
| 373 | class TemporaryFileRegistry { |
| 374 | public: |
| 375 | ~TemporaryFileRegistry() { |
| 376 | for (const std::string& path : paths_) { |
| 377 | std::remove(path.c_str()); |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | std::string Create(const std::string& prefix, const std::string& extension) { |
| 382 | const std::string pid = GetProcessIdString(); |
| 383 | std::string path; |
| 384 | do { |
| 385 | path = BenchmarkTempDirectory() + prefix + "." + pid + "." + |
| 386 | std::to_string(counter_++) + extension; |
| 387 | } while (IsRegularFile(path)); |
| 388 | paths_.push_back(path); |
| 389 | return path; |
| 390 | } |
| 391 | |
| 392 | private: |
| 393 | int counter_ = 0; |
| 394 | std::vector<std::string> paths_; |
| 395 | }; |
| 396 | |
| 397 | TemporaryFileRegistry& GetTemporaryFileRegistry() { |
| 398 | static TemporaryFileRegistry registry; |
| 399 | return registry; |
| 400 | } |
| 401 | |
| 402 | std::vector<std::string> InitializationConfigs() { |
| 403 | std::vector<std::string> configs = { |
| 404 | "hk2s", "hk2t", "jp2t", "s2hk", "s2t", "s2tw", "s2twp", |
| 405 | "t2hk", "t2jp", "t2s", "t2tw", "tw2s", "tw2sp", "tw2t", |
| 406 | }; |
| 407 | #ifdef OPENCC_BENCHMARK_JIEBA_CONFIG_DIR |
| 408 | configs.push_back("s2twp_jieba"); |
| 409 | #endif |
| 410 | return configs; |
| 411 | } |
| 412 | |
| 413 | std::vector<std::string> ConversionConfigs() { |
| 414 | std::vector<std::string> configs = {"s2t", "s2twp"}; |
| 415 | #ifdef OPENCC_BENCHMARK_JIEBA_CONFIG_DIR |
| 416 | configs.push_back("s2twp_jieba"); |
| 417 | #endif |
| 418 | return configs; |
| 419 | } |
| 420 | |
| 421 | std::vector<BenchmarkConfig> BuildBenchmarkConfigs( |
| 422 | const std::vector<std::string>& config_names) { |
| 423 | std::vector<BenchmarkConfig> configs; |
| 424 | configs.reserve(config_names.size() * 2); |
| 425 | for (const std::string& config_name : config_names) { |
| 426 | const std::string source_path = ResolveConfigPath(config_name); |
| 427 | configs.push_back(BenchmarkConfig{config_name + "/ocd2", source_path}); |
| 428 | try { |
| 429 | configs.push_back(BenchmarkConfig{ |
| 430 | config_name + "/text_json", |
| 431 | GetTemporaryTextConfigRegistry().Create(source_path, "text", |
| 432 | "benchmark-text"), |
| 433 | }); |
| 434 | } catch (const FileNotFound&) { |
| 435 | // Some legacy benchmark configs only ship precompiled ocd2 artifacts. |
| 436 | // Skip the text-json variant when there is no source text dictionary. |
| 437 | } |
| 438 | } |
| 439 | return configs; |
| 440 | } |
| 441 | |
| 442 | std::string QuotePath(const std::string& path) { |
| 443 | return "\"" + path + "\""; |
| 444 | } |
| 445 | |
| 446 | std::string WrapSystemCommand(const std::string& command) { |
| 447 | #ifdef _WIN32 |
| 448 | return "\"" + command + "\""; |
| 449 | #else |
| 450 | return command; |
| 451 | #endif |
| 452 | } |
| 453 | |
| 454 | #ifdef OPENCC_BENCHMARK_JIEBA_CONFIG_DIR |
| 455 | bool IsJiebaConfig(const BenchmarkConfig& config) { |
| 456 | return config.name.find("s2twp_jieba/") == 0; |
| 457 | } |
| 458 | #endif |
| 459 | |
| 460 | std::string OpenccBinaryPath() { |
| 461 | return OPENCC_BENCHMARK_OPENCC_PATH; |
| 462 | } |
| 463 | |
| 464 | std::string SourceConfigDirectory() { |
| 465 | return std::string(PROJECT_SOURCE_DIR) + "/data/config"; |
| 466 | } |
| 467 | |
| 468 | std::string BuildDataDirectory() { |
| 469 | return std::string(PROJECT_BINARY_DIR) + "/data"; |
| 470 | } |
| 471 | |
| 472 | struct MeasuredResult { |
| 473 | double loadMs = 0.0; |
| 474 | double convertMs = 0.0; |
| 475 | double writeMs = 0.0; |
| 476 | double totalMs = 0.0; |
| 477 | size_t inputBytes = 0; |
| 478 | size_t outputBytes = 0; |
| 479 | }; |
| 480 | |
| 481 | MeasuredResult ParseMeasuredResult(const std::string& path) { |
| 482 | const std::string content = ReadFile(path); |
| 483 | JSONDocument document; |
| 484 | document.Parse(content.c_str()); |
| 485 | if (document.HasParseError() || !document.IsObject()) { |
| 486 | throw InvalidFormat("Error parsing measured result JSON"); |
| 487 | } |
| 488 | |
| 489 | MeasuredResult result; |
| 490 | if (document.HasMember("load_ms") && document["load_ms"].IsNumber()) { |
| 491 | result.loadMs = document["load_ms"].GetDouble(); |
| 492 | } |
| 493 | if (document.HasMember("convert_ms") && document["convert_ms"].IsNumber()) { |
| 494 | result.convertMs = document["convert_ms"].GetDouble(); |
| 495 | } |
| 496 | if (document.HasMember("write_ms") && document["write_ms"].IsNumber()) { |
| 497 | result.writeMs = document["write_ms"].GetDouble(); |
| 498 | } |
| 499 | if (document.HasMember("total_ms") && document["total_ms"].IsNumber()) { |
| 500 | result.totalMs = document["total_ms"].GetDouble(); |
| 501 | } |
| 502 | if (document.HasMember("input_bytes") && document["input_bytes"].IsUint64()) { |
| 503 | result.inputBytes = static_cast<size_t>(document["input_bytes"].GetUint64()); |
| 504 | } |
| 505 | if (document.HasMember("output_bytes") && |
| 506 | document["output_bytes"].IsUint64()) { |
| 507 | result.outputBytes = |
| 508 | static_cast<size_t>(document["output_bytes"].GetUint64()); |
| 509 | } |
| 510 | return result; |
| 511 | } |
| 512 | |
| 513 | void RunCommandLineConversion(const BenchmarkConfig& config, |
| 514 | const std::string& input_path, |
| 515 | const std::string& output_path, |
| 516 | const std::string& measured_result_path) { |
| 517 | #ifdef OPENCC_BENCHMARK_JIEBA_CONFIG_DIR |
| 518 | if (IsJiebaConfig(config)) { |
| 519 | SetPluginSearchPath(OPENCC_BENCHMARK_JIEBA_PLUGIN_DIR); |
| 520 | } |
| 521 | #endif |
| 522 | |
| 523 | std::string command = QuotePath(OpenccBinaryPath()) + " -i " + |
| 524 | QuotePath(input_path) + " -o " + QuotePath(output_path) + |
| 525 | " -c " + QuotePath(config.path) + " --path " + |
| 526 | QuotePath(BuildDataDirectory()) + " --path " + |
| 527 | QuotePath(SourceConfigDirectory()) + |
| 528 | " --measured_result " + QuotePath(measured_result_path); |
| 529 | const int status = std::system(WrapSystemCommand(command).c_str()); |
| 530 | if (status != 0) { |
| 531 | throw Exception("opencc command failed with status " + |
| 532 | std::to_string(status)); |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | SimpleConverter* Initialize(const BenchmarkConfig& config) { |
| 537 | chdir(PROJECT_BINARY_DIR "/data"); |
| 538 | return new SimpleConverter(config.path); |
| 539 | } |
| 540 | |
| 541 | void Convert(const SimpleConverter* converter, std::string_view text) { |
| 542 | converter->Convert(text); |
| 543 | } |
| 544 | |
| 545 | std::string FormatTimeValue(double time) { |
| 546 | std::ostringstream os; |
| 547 | if (time < 1.0) { |
| 548 | os << std::fixed << std::setprecision(3) << time; |
| 549 | } else if (time < 10.0) { |
| 550 | os << std::fixed << std::setprecision(2) << time; |
| 551 | } else if (time < 100.0) { |
| 552 | os << std::fixed << std::setprecision(1) << time; |
| 553 | } else if (time > 9999999999.0) { |
| 554 | os << std::scientific << std::setprecision(4) << time; |
| 555 | } else { |
| 556 | os << std::fixed << std::setprecision(0) << time; |
| 557 | } |
| 558 | return os.str(); |
| 559 | } |
| 560 | |
| 561 | std::string FormatThroughputValue(const benchmark::BenchmarkReporter::Run& run) { |
| 562 | const auto it = run.counters.find("Throughput"); |
| 563 | if (it == run.counters.end()) { |
| 564 | return ""; |
| 565 | } |
| 566 | |
| 567 | std::ostringstream os; |
| 568 | if (run.run_type == benchmark::BenchmarkReporter::Run::RT_Aggregate && |
| 569 | run.aggregate_unit == benchmark::StatisticUnit::kPercentage) { |
| 570 | os << std::fixed << std::setprecision(2) << (100.0 * it->second.value) |
| 571 | << "%"; |
| 572 | } else { |
| 573 | os << std::fixed << std::setprecision(2) << it->second.value << " MB/s"; |
| 574 | } |
| 575 | return os.str(); |
| 576 | } |
| 577 | |
| 578 | std::string FormatCounterValue(const benchmark::BenchmarkReporter::Run& run, |
| 579 | const char* key, const char* suffix = "") { |
| 580 | const auto it = run.counters.find(key); |
| 581 | if (it == run.counters.end()) { |
| 582 | return ""; |
| 583 | } |
| 584 | |
| 585 | std::ostringstream os; |
| 586 | if (run.run_type == benchmark::BenchmarkReporter::Run::RT_Aggregate && |
| 587 | run.aggregate_unit == benchmark::StatisticUnit::kPercentage) { |
| 588 | os << std::fixed << std::setprecision(2) << (100.0 * it->second.value) |
| 589 | << "%"; |
| 590 | } else { |
| 591 | os << std::fixed << std::setprecision(2) << it->second.value << suffix; |
| 592 | } |
| 593 | return os.str(); |
| 594 | } |
| 595 | |
| 596 | std::string BenchmarkGroupName(const benchmark::BenchmarkReporter::Run& run) { |
| 597 | const std::string name = run.benchmark_name(); |
| 598 | const std::string::size_type slash_pos = name.find('/'); |
| 599 | const std::string prefix = |
| 600 | slash_pos == std::string::npos ? name : name.substr(0, slash_pos); |
| 601 | if (prefix == "BM_Initialization") { |
| 602 | return "Initialization"; |
| 603 | } |
| 604 | if (prefix == "BM_ConvertLongText") { |
| 605 | return "Convert Long Text"; |
| 606 | } |
| 607 | if (prefix == "BM_Convert") { |
| 608 | return "Convert"; |
| 609 | } |
| 610 | if (prefix == "BM_CommandLineLongText") { |
| 611 | return "Command Line Long Text"; |
| 612 | } |
| 613 | if (prefix == "BM_CommandLine") { |
| 614 | return "Command Line"; |
| 615 | } |
| 616 | return prefix; |
| 617 | } |
| 618 | |
| 619 | bool SameCounterNames(const benchmark::UserCounters& lhs, |
| 620 | const benchmark::UserCounters& rhs) { |
| 621 | if (lhs.size() != rhs.size()) { |
| 622 | return false; |
| 623 | } |
| 624 | auto lhs_it = lhs.begin(); |
| 625 | auto rhs_it = rhs.begin(); |
| 626 | while (lhs_it != lhs.end() && rhs_it != rhs.end()) { |
| 627 | if (lhs_it->first != rhs_it->first) { |
| 628 | return false; |
| 629 | } |
| 630 | ++lhs_it; |
| 631 | ++rhs_it; |
| 632 | } |
| 633 | return true; |
| 634 | } |
| 635 | |
| 636 | class ThroughputConsoleReporter : public benchmark::ConsoleReporter { |
| 637 | public: |
| 638 | explicit ThroughputConsoleReporter(OutputOptions opts = OO_Defaults) |
| 639 | : benchmark::ConsoleReporter(opts) {} |
| 640 | |
| 641 | void ReportRuns(const std::vector<Run>& reports) override { |
| 642 | for (const auto& run : reports) { |
| 643 | const std::string group_name = BenchmarkGroupName(run); |
| 644 | const bool group_changed = !printed_header_ || group_name != current_group_; |
| 645 | bool print_header = group_changed; |
| 646 | print_header |= |
| 647 | (output_options_ & OO_Tabular) && |
| 648 | (!SameCounterNames(run.counters, prev_counters_)); |
| 649 | if (print_header) { |
| 650 | if (printed_header_) { |
| 651 | GetOutputStream() << "\n"; |
| 652 | } |
| 653 | current_group_ = group_name; |
| 654 | GetOutputStream() << "[" << current_group_ << "]\n"; |
| 655 | printed_header_ = true; |
| 656 | prev_counters_ = run.counters; |
| 657 | PrintHeader(run); |
| 658 | } |
| 659 | PrintRunData(run); |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | protected: |
| 664 | void PrintHeader(const Run& run) override { |
| 665 | std::ostringstream header; |
| 666 | header << std::left << std::setw(static_cast<int>(name_field_width_)) |
| 667 | << "Benchmark" |
| 668 | << " " << std::right << std::setw(13) << "Time" |
| 669 | << " " << std::setw(15) << "CPU" |
| 670 | << " " << std::setw(12) << "Iterations"; |
| 671 | if (!run.counters.empty()) { |
| 672 | header << " " << std::setw(16) << "Throughput"; |
| 673 | if (run.counters.count("LoadMs") != 0) { |
| 674 | header << " " << std::setw(12) << "LoadMs" |
| 675 | << " " << std::setw(12) << "ConvertMs" |
| 676 | << " " << std::setw(12) << "WriteMs" |
| 677 | << " " << std::setw(12) << "TotalMs"; |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | const std::string line(header.str().size(), '-'); |
| 682 | GetOutputStream() << line << "\n" |
| 683 | << header.str() << "\n" |
| 684 | << line << "\n"; |
| 685 | } |
| 686 | |
| 687 | void PrintRunData(const Run& run) override { |
| 688 | std::ostream& out = GetOutputStream(); |
| 689 | out << std::left << std::setw(static_cast<int>(name_field_width_)) |
| 690 | << run.benchmark_name() << " "; |
| 691 | |
| 692 | if (run.run_type != Run::RT_Aggregate || |
| 693 | run.aggregate_unit == benchmark::StatisticUnit::kTime) { |
| 694 | out << std::right << std::setw(10) << FormatTimeValue(run.GetAdjustedRealTime()) |
| 695 | << " " << std::setw(4) << benchmark::GetTimeUnitString(run.time_unit) |
| 696 | << " " << std::setw(10) << FormatTimeValue(run.GetAdjustedCPUTime()) |
| 697 | << " " << std::setw(4) << benchmark::GetTimeUnitString(run.time_unit) |
| 698 | << " "; |
| 699 | } else { |
| 700 | out << std::right << std::setw(10) << std::fixed << std::setprecision(2) |
| 701 | << (100.0 * run.real_accumulated_time) << " " << std::setw(4) << "%" |
| 702 | << " " << std::setw(10) << std::fixed << std::setprecision(2) |
| 703 | << (100.0 * run.cpu_accumulated_time) << " " << std::setw(4) << "%" |
| 704 | << " "; |
| 705 | } |
| 706 | |
| 707 | out << std::right << std::setw(10) << run.iterations; |
| 708 | |
| 709 | if (!run.counters.empty()) { |
| 710 | out << " " << std::setw(16) << FormatThroughputValue(run); |
| 711 | if (run.counters.count("LoadMs") != 0) { |
| 712 | out << " " << std::setw(12) << FormatCounterValue(run, "LoadMs", " ms") |
| 713 | << " " << std::setw(12) |
| 714 | << FormatCounterValue(run, "ConvertMs", " ms") << " " |
| 715 | << std::setw(12) << FormatCounterValue(run, "WriteMs", " ms") |
| 716 | << " " << std::setw(12) |
| 717 | << FormatCounterValue(run, "TotalMs", " ms"); |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | if (!run.report_label.empty()) { |
| 722 | out << " " << run.report_label; |
| 723 | } |
| 724 | |
| 725 | out << "\n"; |
| 726 | } |
| 727 | |
| 728 | private: |
| 729 | std::string current_group_; |
| 730 | }; |
| 731 | |
| 732 | void SetThroughputCounter(benchmark::State& state, size_t bytes_per_iteration) { |
| 733 | const double total_megabytes = |
| 734 | static_cast<double>(state.iterations()) * |
| 735 | static_cast<double>(bytes_per_iteration) / 1000000.0; |
| 736 | state.counters["Throughput"] = |
| 737 | benchmark::Counter(total_megabytes, benchmark::Counter::kIsRate); |
| 738 | } |
| 739 | |
| 740 | void SetCommandLineCounters(benchmark::State& state, size_t total_input_bytes, |
| 741 | double total_load_ms, double total_convert_ms, |
| 742 | double total_write_ms, double total_total_ms) { |
| 743 | const double throughput = |
| 744 | total_total_ms > 0.0 |
| 745 | ? (static_cast<double>(total_input_bytes) / 1000000.0) / |
| 746 | (total_total_ms / 1000.0) |
| 747 | : 0.0; |
| 748 | const double iterations = static_cast<double>(state.iterations()); |
| 749 | state.counters["Throughput"] = benchmark::Counter(throughput); |
| 750 | state.counters["LoadMs"] = benchmark::Counter(total_load_ms / iterations); |
| 751 | state.counters["ConvertMs"] = |
| 752 | benchmark::Counter(total_convert_ms / iterations); |
| 753 | state.counters["WriteMs"] = benchmark::Counter(total_write_ms / iterations); |
| 754 | state.counters["TotalMs"] = benchmark::Counter(total_total_ms / iterations); |
| 755 | } |
| 756 | |
| 757 | std::string ReadText(const std::string& filename) { |
| 758 | const std::string benchmark_data_dir = PROJECT_SOURCE_DIR "/test/benchmark/"; |
| 759 | const std::string data_path = benchmark_data_dir + filename; |
| 760 | std::ifstream stream(data_path.c_str()); |
| 761 | return std::string((std::istreambuf_iterator<char>(stream)), |
| 762 | std::istreambuf_iterator<char>()); |
| 763 | } |
| 764 | |
| 765 | static void BM_Initialization(benchmark::State& state, |
| 766 | const BenchmarkConfig& config) { |
| 767 | for (auto _ : state) { |
| 768 | const SimpleConverter* converter = Initialize(config); |
| 769 | state.PauseTiming(); |
| 770 | delete converter; |
| 771 | state.ResumeTiming(); |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | static void BM_ConvertLongText(benchmark::State& state, |
| 776 | const BenchmarkConfig& config) { |
| 777 | const std::string text = ReadText("zuozhuan.txt"); |
| 778 | const std::unique_ptr<SimpleConverter> converter(Initialize(config)); |
| 779 | for (auto _ : state) { |
| 780 | Convert(converter.get(), text); |
| 781 | } |
| 782 | SetThroughputCounter(state, text.size()); |
| 783 | } |
| 784 | |
| 785 | static void BM_Convert(benchmark::State& state, const BenchmarkConfig& config, |
| 786 | int iteration) { |
| 787 | std::ostringstream os; |
| 788 | for (int i = 0; i < iteration; i++) { |
| 789 | os << "Open Chinese Convert 開放中文轉換" << i << std::endl; |
| 790 | } |
| 791 | const std::string text = os.str(); |
| 792 | const std::unique_ptr<SimpleConverter> converter(Initialize(config)); |
| 793 | for (auto _ : state) { |
| 794 | Convert(converter.get(), text); |
| 795 | } |
| 796 | SetThroughputCounter(state, text.size()); |
| 797 | } |
| 798 | |
| 799 | static void BM_CommandLineLongText(benchmark::State& state, |
| 800 | const BenchmarkConfig& config) { |
| 801 | const std::string input_path = |
| 802 | GetTemporaryFileRegistry().Create("benchmark-cli-longtext-input", ".txt"); |
| 803 | const std::string output_path = |
| 804 | GetTemporaryFileRegistry().Create("benchmark-cli-longtext-output", ".txt"); |
| 805 | const std::string measured_path = |
| 806 | GetTemporaryFileRegistry().Create("benchmark-cli-longtext-measured", |
| 807 | ".json"); |
| 808 | const std::string text = ReadText("zuozhuan.txt"); |
| 809 | { |
| 810 | std::ofstream stream(input_path.c_str(), std::ios::binary); |
| 811 | stream << text; |
| 812 | } |
| 813 | |
| 814 | MeasuredResult measured; |
| 815 | size_t total_input_bytes = 0; |
| 816 | double total_load_ms = 0.0; |
| 817 | double total_convert_ms = 0.0; |
| 818 | double total_write_ms = 0.0; |
| 819 | double total_total_ms = 0.0; |
| 820 | for (auto _ : state) { |
| 821 | RunCommandLineConversion(config, input_path, output_path, measured_path); |
| 822 | measured = ParseMeasuredResult(measured_path); |
| 823 | total_input_bytes += measured.inputBytes == 0 ? text.size() : measured.inputBytes; |
| 824 | total_load_ms += measured.loadMs; |
| 825 | total_convert_ms += measured.convertMs; |
| 826 | total_write_ms += measured.writeMs; |
| 827 | total_total_ms += measured.totalMs; |
| 828 | } |
| 829 | SetCommandLineCounters(state, total_input_bytes, total_load_ms, |
| 830 | total_convert_ms, total_write_ms, total_total_ms); |
| 831 | } |
| 832 | |
| 833 | static void BM_CommandLine(benchmark::State& state, const BenchmarkConfig& config, |
| 834 | int iteration) { |
| 835 | const std::string input_path = |
| 836 | GetTemporaryFileRegistry().Create("benchmark-cli-input", ".txt"); |
| 837 | const std::string output_path = |
| 838 | GetTemporaryFileRegistry().Create("benchmark-cli-output", ".txt"); |
| 839 | const std::string measured_path = |
| 840 | GetTemporaryFileRegistry().Create("benchmark-cli-measured", ".json"); |
| 841 | |
| 842 | std::ostringstream os; |
| 843 | for (int i = 0; i < iteration; i++) { |
| 844 | os << "Open Chinese Convert 開放中文轉換" << i << std::endl; |
| 845 | } |
| 846 | const std::string text = os.str(); |
| 847 | { |
| 848 | std::ofstream stream(input_path.c_str(), std::ios::binary); |
| 849 | stream << text; |
| 850 | } |
| 851 | |
| 852 | MeasuredResult measured; |
| 853 | size_t total_input_bytes = 0; |
| 854 | double total_load_ms = 0.0; |
| 855 | double total_convert_ms = 0.0; |
| 856 | double total_write_ms = 0.0; |
| 857 | double total_total_ms = 0.0; |
| 858 | for (auto _ : state) { |
| 859 | RunCommandLineConversion(config, input_path, output_path, measured_path); |
| 860 | measured = ParseMeasuredResult(measured_path); |
| 861 | total_input_bytes += measured.inputBytes == 0 ? text.size() : measured.inputBytes; |
| 862 | total_load_ms += measured.loadMs; |
| 863 | total_convert_ms += measured.convertMs; |
| 864 | total_write_ms += measured.writeMs; |
| 865 | total_total_ms += measured.totalMs; |
| 866 | } |
| 867 | SetCommandLineCounters(state, total_input_bytes, total_load_ms, |
| 868 | total_convert_ms, total_write_ms, total_total_ms); |
| 869 | } |
| 870 | |
| 871 | bool RegisterBenchmarks() { |
| 872 | const std::vector<BenchmarkConfig> initialization_configs = |
| 873 | BuildBenchmarkConfigs(InitializationConfigs()); |
| 874 | for (const BenchmarkConfig& config : initialization_configs) { |
| 875 | benchmark::RegisterBenchmark( |
| 876 | ("BM_Initialization/" + config.name).c_str(), |
| 877 | [config](benchmark::State& state) { BM_Initialization(state, config); }) |
| 878 | ->Unit(benchmark::kMicrosecond); |
| 879 | } |
| 880 | |
| 881 | const std::vector<BenchmarkConfig> conversion_configs = |
| 882 | BuildBenchmarkConfigs(ConversionConfigs()); |
| 883 | for (const BenchmarkConfig& config : conversion_configs) { |
| 884 | benchmark::RegisterBenchmark( |
| 885 | ("BM_ConvertLongText/" + config.name).c_str(), |
| 886 | [config](benchmark::State& state) { BM_ConvertLongText(state, config); }) |
| 887 | ->Unit(benchmark::kMillisecond); |
| 888 | } |
| 889 | |
| 890 | for (const BenchmarkConfig& config : conversion_configs) { |
| 891 | for (const int iteration : {100, 1000, 10000, 100000}) { |
| 892 | benchmark::RegisterBenchmark( |
| 893 | ("BM_Convert/" + config.name + "/" + std::to_string(iteration)) |
| 894 | .c_str(), |
| 895 | [config, iteration](benchmark::State& state) { |
| 896 | BM_Convert(state, config, iteration); |
| 897 | }) |
| 898 | ->Unit(benchmark::kMillisecond); |
| 899 | } |
| 900 | } |
| 901 | |
| 902 | for (const BenchmarkConfig& config : conversion_configs) { |
| 903 | benchmark::RegisterBenchmark( |
| 904 | ("BM_CommandLineLongText/" + config.name).c_str(), |
| 905 | [config](benchmark::State& state) { |
| 906 | BM_CommandLineLongText(state, config); |
| 907 | }) |
| 908 | ->Unit(benchmark::kMillisecond) |
| 909 | ->MinTime(0.01); |
| 910 | } |
| 911 | |
| 912 | for (const BenchmarkConfig& config : conversion_configs) { |
| 913 | for (const int iteration : {100, 1000, 10000, 100000}) { |
| 914 | benchmark::RegisterBenchmark( |
| 915 | ("BM_CommandLine/" + config.name + "/" + std::to_string(iteration)) |
| 916 | .c_str(), |
| 917 | [config, iteration](benchmark::State& state) { |
| 918 | BM_CommandLine(state, config, iteration); |
| 919 | }) |
| 920 | ->Unit(benchmark::kMillisecond) |
| 921 | ->MinTime(0.01); |
| 922 | } |
| 923 | } |
| 924 | return true; |
| 925 | } |
| 926 | |
| 927 | const bool kBenchmarksRegistered = RegisterBenchmarks(); |
| 928 | |
| 929 | } // namespace |
| 930 | |
| 931 | } // namespace opencc |
| 932 | |
| 933 | int main(int argc, char** argv) { |
| 934 | ::benchmark::Initialize(&argc, argv); |
| 935 | if (::benchmark::ReportUnrecognizedArguments(argc, argv)) { |
| 936 | return 1; |
| 937 | } |
| 938 | opencc::ThroughputConsoleReporter reporter; |
| 939 | ::benchmark::RunSpecifiedBenchmarks(&reporter); |
| 940 | ::benchmark::Shutdown(); |
| 941 | return 0; |
| 942 | } |