From ad2bf148c3b23287765614ac424cb17701c7916f Mon Sep 17 00:00:00 2001 From: teridax Date: Mon, 1 May 2023 15:51:17 +0200 Subject: [PATCH] updated comments --- sparse_vector/src/main.rs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/sparse_vector/src/main.rs b/sparse_vector/src/main.rs index 67e9298..88985d9 100644 --- a/sparse_vector/src/main.rs +++ b/sparse_vector/src/main.rs @@ -1,19 +1,39 @@ +/** + * _ _ _ _ + * __ ___ __(_) |_| |_ ___ _ __ | |__ _ _ + * \ \ /\ / / '__| | __| __/ _ \ '_ \ | '_ \| | | | + * \ V V /| | | | |_| || __/ | | | | |_) | |_| | + * \_/\_/ |_| |_|\__|\__\___|_| |_| |_.__/ \__, | + * |___/ + * ____ __ __ _ + * / ___|_ _____ _ __ \ \ / /__ __ _ ___| | + * \___ \ \ / / _ \ '_ \ \ \ / / _ \ / _` |/ _ \ | + * ___) \ V / __/ | | | \ V / (_) | (_| | __/ | + * |____/ \_/ \___|_| |_| \_/ \___/ \__, |\___|_| + * |___/ + * Licensed under the GPLv2 License, Version 2.0 (the "License"); + * Copyright (c) Sven Vogel + */ + use std::collections::BTreeMap; use std::time::Instant; use bytesize::ByteSize; use rand::Rng; use jemalloc_ctl::{stats, epoch}; +// we use a custom allocator for tracking heap allocations #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; -/// Only stores more efficiently when at least 50% of all elements are zeros +/// Wrapper struct around a BinaryTreeMap that stores the non zero elements of a vector by using the indices +/// as keys in the tree. pub struct SparseVec { map: BTreeMap } impl SparseVec { + /// Compute the dot product of two vectors pub fn dot(&self, other: &SparseVec) -> f64 { let mut sum = 0.0; @@ -24,14 +44,20 @@ impl SparseVec { sum } + /// Create a new SparseVec with a theoretical size of `elements`. `non_null`is the ration of non zero elements + /// in the sparse vector. A value of 0.0 means that all elements are zero. pub fn new(elements: usize, non_null: f64) -> Self { + // calculate the number of non-zero elements let non_zero_elements = (elements as f64 * non_null) as usize; + // create the map let mut map = BTreeMap::new(); let mut rng = rand::thread_rng(); + // generate some random values for i in 0..non_zero_elements { + // generate a random index that continuesly increases let idx = i as f32 / non_zero_elements as f32 * (elements as f32 - 4.0) + rng.gen_range(0.0..3.0); map.insert(idx as usize, 0.5); @@ -43,6 +69,7 @@ impl SparseVec { } } +// rudimentary macro for timing a block of code macro_rules! time { ($name:literal, $block:expr) => {{ let start = Instant::now();