Skip to content

Commit

Permalink
为avl树添加benchmark
Browse files Browse the repository at this point in the history
  • Loading branch information
copi143 committed Oct 25, 2024
1 parent 665b6e3 commit 95b90d5
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 2 deletions.
2 changes: 1 addition & 1 deletion include/data-structure/avltree.h
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ static avltree_t avltree_balance(avltree_t node) {
}

static avltree_t avltree_alloc(int32_t key, void *value) {
avltree_t node = malloc(sizeof(*node));
avltree_t node = (avltree_t)malloc(sizeof(*node));
node->key = key;
node->value = value;
node->left = null;
Expand Down
1 change: 1 addition & 0 deletions test/c/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
benchmark(c-rbtree rbtree-bench.cpp)
gtest(c-rbtree rbtree-test.cpp)
benchmark(c-avltree avltree-bench.cpp)
73 changes: 73 additions & 0 deletions test/c/avltree-bench.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#include <benchmark/benchmark.h>
#include <cstring>
#include <random>

#define NO_STD 0
#define AVL_IMPLEMENTATION
extern "C" {
#include <data-structure/avltree.h>
}

std::vector<i32> keys;

std::vector<i32> generate_nums(size_t length, ssize_t seed) {
std::default_random_engine rng(seed);
std::vector<i32> result;
result.reserve(length);
avltree_t tree = null;
for (size_t i = 0; i < length;) {
i32 key = rng();
if (avltree_get_node(tree, key) == null) {
result.push_back(key);
avltree_insert(tree, key, null);
i++;
}
}
avltree_free(tree);
return result;
}

static void BM_INSERT(benchmark::State &state) {
::keys = generate_nums(10000, 114514);
for (auto _ : state) {
avltree_t tree = null;
for (const auto key : keys) {
avltree_insert(tree, key, null);
}
benchmark::DoNotOptimize(tree);
avltree_free(tree);
}
}

static void BM_GET(benchmark::State &state) {
avltree_t tree = null;
for (const auto key : keys) {
avltree_insert(tree, key, null);
}
for (auto _ : state) {
for (const auto key : keys) {
auto val = avltree_get(tree, key);
benchmark::DoNotOptimize(val);
}
}
avltree_free(tree);
}

static void BM_DELETE(benchmark::State &state) {
for (auto _ : state) {
avltree_t tree = null;
for (const auto key : keys) {
avltree_insert(tree, key, null);
}
for (const auto key : keys) {
avltree_delete(tree, key);
}
benchmark::DoNotOptimize(tree);
}
}

BENCHMARK(BM_INSERT);
BENCHMARK(BM_GET);
BENCHMARK(BM_DELETE);

BENCHMARK_MAIN();
1 change: 0 additions & 1 deletion test/c/rbtree-bench.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#include <benchmark/benchmark.h>
#include <cstring>
#include <random>
#include <string>

#define NO_STD 0
#define RBTREE_IMPLEMENTATION
Expand Down

0 comments on commit 95b90d5

Please sign in to comment.