File: parse_benchmark.cpp

package info (click to toggle)
tomlplusplus 3.3.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,184 kB
  • sloc: cpp: 35,145; ansic: 2,220; python: 983; makefile: 25; sh: 17
file content (81 lines) | stat: -rw-r--r-- 2,363 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// This file is a part of toml++ and is subject to the the terms of the MIT license.
// Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
// See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
// SPDX-License-Identifier: MIT

// This example is just a short-n-shiny benchmark.

#include "examples.h"
#include <toml++/toml.h>

using namespace std::string_view_literals;

static constexpr size_t iterations = 10000;

int main(int argc, char** argv)
{
	const auto file_path = std::string(argc > 1 ? std::string_view{ argv[1] } : "benchmark_data.toml"sv);

	// read the file into a string first to remove file I/O from the benchmark
	std::string file_content;
	{
		std::ifstream file(file_path, std::ifstream::in | std::ifstream::binary | std::ifstream::ate);
		if (!file)
		{
			std::cerr << "File '"sv << file_path << "'could not be opened for reading\n"sv;
			return -1;
		}

		const auto file_size = file.tellg();
		if (file_size == -1)
		{
			std::cerr << "File '"sv << file_path << "' could not be opened for reading\n"sv;
			return -1;
		}
		file.seekg(0, std::ifstream::beg);

		file_content.resize(static_cast<size_t>(file_size));
		file.read(file_content.data(), static_cast<std::streamsize>(file_size));
		if (!file.eof() && !file)
		{
			std::cerr << "Failed to read contents of file '"sv << file_path << "'\n"sv;
			return -1;
		}
	}

	// parse once to make sure it isn't garbage
	{
#if TOML_EXCEPTIONS
		try
		{
			const auto result = toml::parse(file_content, file_path);
		}
		catch (const toml::parse_error& err)
		{
			std::cerr << err << "\n";
			return 1;
		}
#else
		const auto result = toml::parse(file_content, file_path);
		if (!result)
		{
			std::cerr << result.error() << "\n";
			return 1;
		}
#endif
	}

	// run the benchmark
	std::cout << "Parsing '"sv << file_path << "' "sv << iterations << " times...\n"sv;

	const auto start = std::chrono::steady_clock::now();
	for (size_t i = 0; i < iterations; i++)
		std::ignore = toml::parse(file_content, file_path);
	const auto cumulative_sec =
		std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - start).count();
	const auto mean_sec = cumulative_sec / static_cast<double>(iterations);
	std::cout << "  total: "sv << cumulative_sec << " s\n"sv
			  << "   mean: "sv << mean_sec << " s\n"sv;

	return 0;
}