Skip to content

Commit 208a0d7

Browse files
committed
Add HierarchicalNSW::indexFileSize() function for precise memory footprint control
1 parent 2c6f244 commit 208a0d7

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

hnswlib/hnswalg.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,32 @@ class HierarchicalNSW : public AlgorithmInterface<dist_t> {
595595
max_elements_ = new_max_elements;
596596
}
597597

598+
size_t indexFileSize() const {
599+
size_t size = 0;
600+
size += sizeof(offsetLevel0_);
601+
size += sizeof(max_elements_);
602+
size += sizeof(cur_element_count);
603+
size += sizeof(size_data_per_element_);
604+
size += sizeof(label_offset_);
605+
size += sizeof(offsetData_);
606+
size += sizeof(maxlevel_);
607+
size += sizeof(enterpoint_node_);
608+
size += sizeof(maxM_);
609+
610+
size += sizeof(maxM0_);
611+
size += sizeof(M_);
612+
size += sizeof(mult_);
613+
size += sizeof(ef_construction_);
614+
615+
size += cur_element_count * size_data_per_element_;
616+
617+
for (size_t i = 0; i < cur_element_count; i++) {
618+
unsigned int linkListSize = element_levels_[i] > 0 ? size_links_per_element_ * element_levels_[i] : 0;
619+
size += sizeof(linkListSize);
620+
size += linkListSize;
621+
}
622+
return size;
623+
}
598624

599625
void saveIndex(const std::string &location) {
600626
std::ofstream output(location, std::ios::binary);

python_bindings/bindings.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,9 @@ class Index {
218218
this->num_threads_default = num_threads;
219219
}
220220

221+
void indexFileSize() const {
222+
appr_alg->indexFileSize();
223+
}
221224

222225
void saveIndex(const std::string &path_to_index) {
223226
appr_alg->saveIndex(path_to_index);
@@ -904,6 +907,7 @@ PYBIND11_PLUGIN(hnswlib) {
904907
.def("get_ids_list", &Index<float>::getIdsList)
905908
.def("set_ef", &Index<float>::set_ef, py::arg("ef"))
906909
.def("set_num_threads", &Index<float>::set_num_threads, py::arg("num_threads"))
910+
.def("index_file_size", &Index<float>::indexFileSize)
907911
.def("save_index", &Index<float>::saveIndex, py::arg("path_to_index"))
908912
.def("load_index",
909913
&Index<float>::loadIndex,

0 commit comments

Comments
 (0)