Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce the number of dependencies #146

Merged
merged 3 commits into from
Sep 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,22 @@ cirrus-ci = { repository = "jonhoo/inferno" }
codecov = { repository = "jonhoo/inferno", branch = "master", service = "github" }

[features]
default = ["cli"]
default = ["cli", "multithreaded"]
cli = ["structopt", "env_logger"]
multithreaded = ["chashmap", "crossbeam", "num_cpus"]

[dependencies]
chashmap = "2.2"
crossbeam = "0.7"
chashmap = { version = "2.2", optional = true }
crossbeam = { version = "0.7", optional = true }
env_logger = { version = "0.6.0", optional = true }
fnv = "1.0.3"
indexmap = "1.0"
itoa = "0.4.3"
lazy_static = "1.3.0"
log = "0.4"
num_cpus = "1.10"
num_cpus = { version = "1.10", optional = true }
num-format = { version = "0.4", default-features = false }
quick-xml = { version = "0.15", default-features = false }
rand = "0.7"
quick-xml = { version = "0.16", default-features = false }
rgb = "0.8.13"
str_stack = "0.1"
structopt = { version = "0.2", optional = true }
Expand Down
54 changes: 46 additions & 8 deletions src/collapse/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ use std::io;
use std::mem;
use std::sync::Arc;

#[cfg(feature = "multithreaded")]
use chashmap::CHashMap;
#[cfg(feature = "multithreaded")]
use crossbeam::channel;

use fnv::FnvHashMap;
use lazy_static::lazy_static;

Expand All @@ -26,11 +29,18 @@ const NBYTES_PER_STACK_GUESS: usize = 1024;

const RUST_HASH_LENGTH: usize = 17;

#[cfg(feature = "multithreaded")]
lazy_static! {
#[doc(hidden)]
pub static ref DEFAULT_NTHREADS: usize = num_cpus::get();
}

#[cfg(not(feature = "multithreaded"))]
lazy_static! {
#[doc(hidden)]
pub static ref DEFAULT_NTHREADS: usize = 1;
}

/// Private trait for internal library authors.
///
/// If you implement this trait, your type will implement the public-facing
Expand Down Expand Up @@ -154,6 +164,15 @@ pub trait CollapsePrivate: Send + Sized {
occurrences.write_and_clear(writer)
}

#[cfg(not(feature = "multithreaded"))]
fn collapse_multi_threaded<R>(&mut self, _: R, _: &mut Occurrences) -> io::Result<()>
where
R: io::BufRead,
{
unimplemented!();
}

#[cfg(feature = "multithreaded")]
fn collapse_multi_threaded<R>(
&mut self,
mut reader: R,
Expand Down Expand Up @@ -332,32 +351,48 @@ pub trait CollapsePrivate: Send + Sized {
#[derive(Clone, Debug)]
pub enum Occurrences {
SingleThreaded(FnvHashMap<String, usize>),
#[cfg(feature = "multithreaded")]
MultiThreaded(Arc<CHashMap<String, usize>>),
}

impl Occurrences {
#[cfg(feature = "multithreaded")]
pub(crate) fn new(nthreads: usize) -> Self {
assert_ne!(nthreads, 0);
if nthreads == 1 {
let map = FnvHashMap::with_capacity_and_hasher(
CAPACITY_HASHMAP,
fnv::FnvBuildHasher::default(),
);
Occurrences::SingleThreaded(map)
Self::new_single_threaded()
} else {
let map = CHashMap::with_capacity(CAPACITY_HASHMAP);
let arc = Arc::new(map);
Occurrences::MultiThreaded(arc)
Self::new_multi_threaded()
}
}

#[cfg(not(feature = "multithreaded"))]
pub(crate) fn new(nthreads: usize) -> Self {
assert_ne!(nthreads, 0);
Self::new_single_threaded()
}

fn new_single_threaded() -> Self {
let map =
FnvHashMap::with_capacity_and_hasher(CAPACITY_HASHMAP, fnv::FnvBuildHasher::default());
Occurrences::SingleThreaded(map)
}

#[cfg(feature = "multithreaded")]
fn new_multi_threaded() -> Self {
let map = CHashMap::with_capacity(CAPACITY_HASHMAP);
let arc = Arc::new(map);
Occurrences::MultiThreaded(arc)
}

/// Inserts a key-count pair into the map. If the map did not have this key
/// present, `None` is returned. If the map did have this key present, the
/// value is updated, and the old value is returned.
pub(crate) fn insert(&mut self, key: String, count: usize) -> Option<usize> {
use self::Occurrences::*;
match self {
SingleThreaded(map) => map.insert(key, count),
#[cfg(feature = "multithreaded")]
MultiThreaded(arc) => arc.insert(key, count),
}
}
Expand All @@ -369,6 +404,7 @@ impl Occurrences {
use self::Occurrences::*;
match self {
SingleThreaded(map) => *map.entry(key).or_insert(0) += count,
#[cfg(feature = "multithreaded")]
MultiThreaded(arc) => arc.upsert(key, || count, |v| *v += count),
}
}
Expand All @@ -377,6 +413,7 @@ impl Occurrences {
use self::Occurrences::*;
match self {
SingleThreaded(_) => false,
#[cfg(feature = "multithreaded")]
MultiThreaded(_) => true,
}
}
Expand All @@ -394,6 +431,7 @@ impl Occurrences {
writeln!(writer, "{} {}", key, value)?;
}
}
#[cfg(feature = "multithreaded")]
MultiThreaded(ref mut arc) => {
let map = match Arc::get_mut(arc) {
Some(map) => map,
Expand Down
10 changes: 7 additions & 3 deletions src/flamegraph/color/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;

use rand::prelude::*;
use rgb::RGB8;

pub use self::palette_map::PaletteMap;
Expand Down Expand Up @@ -328,14 +327,19 @@ fn rgb_components_for_palette(palette: Palette, name: &str, v1: f32, v2: f32, v3
}
}

pub(super) fn color(palette: Palette, hash: bool, name: &str, thread_rng: &mut ThreadRng) -> Color {
pub(super) fn color(
palette: Palette,
hash: bool,
name: &str,
mut rng: impl FnMut() -> f32,
) -> Color {
let (v1, v2, v3) = if hash {
let name_hash = namehash(name.bytes());
let reverse_name_hash = namehash(name.bytes().rev());

(name_hash, reverse_name_hash, reverse_name_hash)
} else {
(thread_rng.gen(), thread_rng.gen(), thread_rng.gen())
(rng(), rng(), rng())
};

rgb_components_for_palette(palette, name, v1, v2, v3)
Expand Down
1 change: 1 addition & 0 deletions src/flamegraph/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ macro_rules! args {
mod attrs;
pub mod color;
mod merge;
mod rand;
mod svg;

use std::fs::File;
Expand Down
77 changes: 77 additions & 0 deletions src/flamegraph/rand.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use std::cell::RefCell;

pub struct XorShift64 {
a: u64,
}

impl XorShift64 {
pub fn new(seed: u64) -> XorShift64 {
XorShift64 { a: seed }
}

pub fn next(&mut self) -> u64 {
let mut x = self.a;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.a = x;
x
}

pub fn next_f64(&mut self) -> f64 {
sample(self.next())
}
}

thread_local! {
pub static RNG: RefCell<XorShift64> = RefCell::new(XorShift64::new(1234));
}

// Copied from `rand` with minor modifications.
fn sample(value: u64) -> f64 {
let fraction_bits = 52;

// Multiply-based method; 24/53 random bits; [0, 1) interval.
// We use the most significant bits because for simple RNGs
// those are usually more random.
let float_size = std::mem::size_of::<f64>() as u32 * 8;
let precision = fraction_bits + 1;
let scale = 1.0 / ((1_u64 << precision) as f64);

let value = value >> (float_size - precision);
scale * (value as f64)
}

pub fn thread_rng() -> impl Fn() -> f32 {
|| RNG.with(|rng| rng.borrow_mut().next_f64() as f32)
}

#[test]
fn test_rng() {
const ITERATIONS: usize = 10000;

let mut rng = XorShift64::new(1234);
let mut sum = rng.next_f64();
let mut min = sum;
let mut max = sum;
for _ in 0..ITERATIONS - 1 {
let value = rng.next_f64();
sum += value;
if value < min {
min = value;
}
if value > max {
max = value;
}
}

let avg = sum / ITERATIONS as f64;

// Make sure the RNG is uniform.
assert!(min >= 0.000);
assert!(min <= 0.001);
assert!(max <= 1.000);
assert!(max >= 0.999);
assert!(avg >= 0.490);
assert!(avg <= 0.510);
}