Benchmarking

Is it really faster to use multiple threads? How many threads should we be using? Rather than guessing, let us benchmark the performances.

Benchmarking consists into executing a task a certain number of times and averaging its execution time over the multiple executions.

Rust has two types handy for dealing with type: Instant, which represents in point in time, and Duration which represents, well, a duration. Instant::now() is the current instant in time, and Instant::elapsed(start) returns a Duration since the instant start.

Also, a Duration can be divided by an integer (of type u32) and return a Duration. It means that if you do something like:

    let start = Instant::now();
    for _ in 0..times {   // Here times is a u32
        do_something();
    }
    let mean_duration = Instant::elapsed(start) / times;

you will get the average time spent to execute do_something() in mean_duration. Also, a Duration implements Debug and will print something like "100 milliseconds" or "3.7 seconds".

Now that you know all this…

Exercise 3.a: Implement a benchmark() function which counts the characters' occurrences over n threads by executing the count_chars_parallel() function times times and returns the result:

fn benchmark<S: AsRef<str> + Sync>(input: &[S], n: usize, times: u32) -> Duration

Exercise 3.b: Implement a benchmark_all() function which calls benchmark() with 1 thread to max threads and prints the results:

fn benchmark_all<S: AsRef<str> + Sync>(input: &[S], max: usize, times: u32)

Exercise 3.c: Call the benchmark_all() function in your main program and look at the result.

See them decrease when you go over the number of cores on your machine.