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
|
#include <algorithm>
#include <random>
void AlgorithmBenchmarks()
{
std::cout << "=== Algorithm Performance Benchmarks ===" << std::endl;
const int dataSize = 100000;
std::vector<int> originalData;
// 生成随机数据
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 1000000);
for (int i = 0; i < dataSize; ++i)
{
originalData.push_back(dis(gen));
}
BenchmarkSuite suite;
// 排序算法比较
suite.AddBenchmark("std::sort", [&]() {
std::vector<int> data = originalData;
std::sort(data.begin(), data.end());
}, 10);
suite.AddBenchmark("std::stable_sort", [&]() {
std::vector<int> data = originalData;
std::stable_sort(data.begin(), data.end());
}, 10);
// 查找算法比较(需要排序后的数据)
std::vector<int> sortedData = originalData;
std::sort(sortedData.begin(), sortedData.end());
int searchValue = sortedData[dataSize / 2];
suite.AddBenchmark("Linear search", [&]() {
auto it = std::find(sortedData.begin(), sortedData.end(), searchValue);
volatile bool found = (it != sortedData.end());
}, 100);
suite.AddBenchmark("Binary search", [&]() {
volatile bool found = std::binary_search(sortedData.begin(), sortedData.end(), searchValue);
}, 100);
// 数学运算比较
suite.AddBenchmark("Accumulate", [&]() {
volatile long long sum = std::accumulate(originalData.begin(), originalData.end(), 0LL);
}, 50);
suite.AddBenchmark("Manual sum", [&]() {
volatile long long sum = 0;
for (int value : originalData)
{
sum += value;
}
}, 50);
suite.PrintAllResults();
suite.PrintComparison();
}
|