Skip to content

Commit

Permalink
Skip building index when loading a tree from a file
Browse files Browse the repository at this point in the history
While benchmarking, it turned out that constructing a tree immediately
built its index. Calling loadIndex() afterwards did practically nothing.

This commit adds an enum to allow passing additional flags like
`SkipInitialBuildIndex` to allow loading a tree without the initial
index build. Greatly reduces startup time for large prebuilt trees.
  • Loading branch information
haraldF committed May 2, 2022
1 parent c52ae8d commit 7bc8cd5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
4 changes: 3 additions & 1 deletion examples/saveload_example.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,11 @@ void kdtree_save_load_demo(const size_t N)
{
// Important: construct the index associated to the same dataset, since
// data points are NOT stored in the binary file.
// Note - set KDTreeSingleIndexAdaptor::SkipInitialBuildIndex, otherwise the tree
// builds an index that'll be overwritten via loadIndex
my_kd_tree_t index(
3 /*dim*/, cloud,
nanoflann::KDTreeSingleIndexAdaptorParams(10 /* max leaf */));
nanoflann::KDTreeSingleIndexAdaptorParams(10 /* max leaf */, nanoflann::KDTreeSingleIndexAdaptorFlags::SkipInitialBuildIndex));

std::ifstream f("index.bin", std::ofstream::binary);

Expand Down
19 changes: 16 additions & 3 deletions include/nanoflann.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -648,15 +648,26 @@ struct metric_SO3 : public Metric
/** @addtogroup param_grp Parameter structs
* @{ */

enum class KDTreeSingleIndexAdaptorFlags {
None = 0,
SkipInitialBuildIndex = 1
};

inline std::underlying_type<KDTreeSingleIndexAdaptorFlags>::type operator&(KDTreeSingleIndexAdaptorFlags lhs, KDTreeSingleIndexAdaptorFlags rhs) {
using underlying = typename std::underlying_type<KDTreeSingleIndexAdaptorFlags>::type;
return static_cast<underlying>(lhs) & static_cast<underlying>(rhs);
}

/** Parameters (see README.md) */
struct KDTreeSingleIndexAdaptorParams
{
KDTreeSingleIndexAdaptorParams(size_t _leaf_max_size = 10)
: leaf_max_size(_leaf_max_size)
KDTreeSingleIndexAdaptorParams(size_t _leaf_max_size = 10, KDTreeSingleIndexAdaptorFlags _flags = KDTreeSingleIndexAdaptorFlags::None)
: leaf_max_size(_leaf_max_size), flags(_flags)
{
}

size_t leaf_max_size;
KDTreeSingleIndexAdaptorFlags flags;
};

/** Search options for KDTreeSingleIndexAdaptor::findNeighbors() */
Expand Down Expand Up @@ -1353,7 +1364,9 @@ class KDTreeSingleIndexAdaptor
if (DIM > 0) BaseClassRef::dim = DIM;
BaseClassRef::m_leaf_max_size = params.leaf_max_size;

buildIndex();
if (index_params.flags & KDTreeSingleIndexAdaptorFlags::SkipInitialBuildIndex) {
buildIndex();
}
}

/**
Expand Down

0 comments on commit 7bc8cd5

Please sign in to comment.