Strange performance of f64::log

Good evening,
for a performance critical piece of code I have just benchmarked the logarithm functions implemented in Rust against each other. The results leave me puzzled:
10^8 logs has this computation times:
f64::ln -> 6.092091879 s
f64::log2 -> 6.691914975 s
f64::log10 -> 9.801576907 s
f64::log(10.) -> 6.176421214 s

If these results were correct log2 and log10 are SOLWER then log(10.) or log(2.) which would indicate erroneous implementation. Since I am not a compiler engineer I am certain, that my test is wrong so please help me to understand why I am getting these results. These reulsts were obtained with cargo run --release
My test code:

use std::time::{Duration, Instant};

fn benchmark_logarithm<F>(log_func: F, input: f64, iterations: usize) -> Duration
where
    F: Fn(f64) -> f64,
{
    let start = Instant::now();
    let mut res = 0.;
    for i in 0..iterations {
        res += log_func(input * i as f64);
    }
    let time = start.elapsed();
    println!("{:?}", res);
    time
}

fn main() {
    let input = 12345.6789_f64;
    let iterations = 10E8 as usize;

    // Benchmark ln (natural logarithm)
    let ln_duration = benchmark_logarithm(f64::ln, input, iterations);
    println!("Time taken for ln: {:?}", ln_duration);

    // Benchmark log2 (base 2 logarithm)
    let log2_duration = benchmark_logarithm(f64::log2, input, iterations);
    println!("Time taken for log2: {:?}", log2_duration);

    // Benchmark log10 (base 10 logarithm)
    let log10_duration = benchmark_logarithm(f64::log10, input, iterations);
    println!("Time taken for log10: {:?}", log10_duration);

    // Benchmark log (logarithm with arbitrary base)
    let log_duration = benchmark_logarithm(|x| x.log(10.0), input, iterations);
    println!("Time taken for log(base 10): {:?}", log_duration);
}

All the best
Henrik

log2 and log10 are more accurate than log(10.0) and thus a bit slower.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.