What's the reason for iteration runtime being so much higher than runtime of consecutive steps?

Viewed 40

[PLAYGROUND]

I believe the below result is self-explanatory. The final meta-measurement proves what I suspected (that measuring itself takes this much time) to be false. The first iteration's runtime is on average more than 4 times higher than consecutive steps + 3 measurements' time.

What's the reason for that?

use std::time::Instant;

fn main() {
    let v:Vec<(i128,i128)>=vec![
        (23,55007766),
        (45,55884433),
        (42,22663355)
    ];
    for i in v{
        let now_ = Instant::now();
            let now = Instant::now();
            let part1 = i.0*i.1;
            let then = Instant::now();
            println!("runtime_part1: {} ns",(then-now).as_nanos());
            
            let now = Instant::now();
            let part2 = part1*i.1;
            let then = Instant::now();
            println!("runtime_part2: {} ns",(then-now).as_nanos());
            
            let now = Instant::now();
            let part3 = i.0+part2;
            let then = Instant::now();
            println!("runtime_part3: {} ns",(then-now).as_nanos());
        let then_ = Instant::now();
        println!("runtime_iter: {} ns",(then_-now_).as_nanos());
    };
    
    let now = Instant::now();
        let now_ = Instant::now();
        (|| 123123*123123);
        let then_ = Instant::now();
        println!("print: {} ns",(then_-now_).as_nanos());
    let then = Instant::now();
    println!("runtime_measurement: {} ns",(then-now).as_nanos());
}
runtime_part1: 30 ns
runtime_part2: 50 ns
runtime_part3: 40 ns
runtime_iter: 23121 ns
runtime_part1: 40 ns
runtime_part2: 40 ns
runtime_part3: 30 ns
runtime_iter: 2440 ns
runtime_part1: 30 ns
runtime_part2: 40 ns
runtime_part3: 30 ns
runtime_iter: 2390 ns
print: 30 ns
runtime_measurement: 960 ns
0 Answers
Related