我在Heap vs Binary Search Tree (BST)处将BST和Heap进行了比较,但是当我尝试对两者进行基准测试并比较结果时,我无法解释BST的数据。
首先,我确认标准库确实使用了红黑树:What is the underlying data structure of a STL set in C++?
然后我运行了这个基准测试。
main.cpp
#include <chrono>
#include <iostream>
#include <random>
#include <set>
int main(int argc, char **argv) {
size_t i, n;
std::set<int> bst;
std::random_device dev;
unsigned int seed = dev();
std::mt19937 prng(seed);
std::uniform_int_distribution<> dist;
if (argc > 1) {
n = std::stoi(argv[1]);
} else {
n = 1000000;
}
for (i = 0; i < n; ++i) {
auto random_value = dist(prng);
auto start = std::chrono::steady_clock::now();
bst.insert(random_value);
auto end = std::chrono::steady_clock::now();
auto dt_bst = end - start;
std::cout << random_value << " "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(dt_bst).count() << std::endl;
}
}
plot.gnuplot:
#!/usr/bin/env gnuplot
set terminal png size 1024, 1024
set output "bst_vs_heap.png"
set title "BST insert time"
set xlabel "size"
set ylabel "nanoseconds"
plot "main.dat" using 2 notitle
编译,运行和绘图:
g++ -ggdb3 -O3 -std=c++17 -Wall -Wextra -pedantic-errors -o main.out main.cpp
./main.out 10000000 > main.dat
./plot.gnuplot
结果:
为什么在理论数据结构中我看不到一条很好的对数曲线,而是一条带有一些离群值的恒定线?
Ubuntu 18.04,GCC 7.3,Intel i7-7820HQ CPU,DDR4 2400 MHz RAM,联想Thinkpad P51。
答案 0 :(得分:10)
如注释中所述,时钟可能不够准确,因此我尝试将一堆插入片段分组在一起并计时以改善信噪比,并且它起作用了,我现在可以看到对数:< / p>
#include <chrono>
#include <iostream>
#include <random>
#include <set>
int main(int argc, char **argv) {
size_t i, j, n, granule;
std::set<int> bst;
std::random_device dev;
unsigned int seed = dev();
std::mt19937 prng(seed);
std::uniform_int_distribution<> dist;
int *randoms;
if (argc > 1) {
n = std::stoi(argv[1]);
} else {
n = 1000000;
}
if (argc > 2) {
granule = std::stoi(argv[2]);
} else {
granule = 10;
}
randoms = new int[granule];
for (i = 0; i < n / granule; ++i) {
for (j = 0; j < granule; ++j) {
randoms[j] = dist(prng);
}
auto start = std::chrono::high_resolution_clock::now();
for (j = 0; j < granule; ++j) {
bst.insert(randoms[j]);
}
auto end = std::chrono::high_resolution_clock::now();
auto dt_bst = end - start;
std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(dt_bst).count() << std::endl;
}
delete[] randoms;
}
命令:
./main.out 100000000 10000
图: