-
-
Save rust-play/3bd45555b9e6faef2b1426712e4e7601 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use criterion::{black_box, criterion_group, criterion_main, Criterion}; | |
use num::{BigUint, CheckedAdd, One, Zero}; | |
use std::iter; | |
const N: usize = 50000; | |
// (1) ジェネリック + checked_add + Option + successors 版: 元の>>295と完全に同じコード | |
fn fibonacci_iter_1<T: Zero + One + CheckedAdd>() -> impl Iterator<Item = T> { | |
let mut oq = Some(T::one()); | |
iter::successors(Some(T::zero()), move |p| { | |
let q = oq.take()?; | |
oq = q.checked_add(p); | |
Some(q) | |
}) | |
} | |
// >>481 iter | |
fn fibonacci_biguint_iter() -> impl Iterator<Item = BigUint> { | |
let mut p = BigUint::zero(); | |
let mut q = BigUint::one(); | |
iter::once(p.clone()).chain(iter::from_fn(move || { | |
p += &q; | |
std::mem::swap(&mut p, &mut q); | |
Some(p.clone()) | |
})) | |
} | |
pub fn criterion_benchmark(c: &mut Criterion) { | |
c.bench_function("fibonacci_iter_1", |b| { | |
b.iter(|| fibonacci_iter_1::<BigUint>().nth(black_box(N))) | |
}); | |
c.bench_function("fibonacci_biguint_iter", |b| { | |
b.iter(|| fibonacci_biguint_iter().nth(black_box(N))) | |
}); | |
} | |
criterion_group!(benches, criterion_benchmark); | |
criterion_main!(benches); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment