代码之家  ›  专栏  ›  技术社区  ›  Brian Obot

在Rust中使用Instant::now调用时,两个空函数会产生不同的运行时

  •  -4
  • Brian Obot  · 技术社区  · 6 月前

    我在rust中编写了两个空函数,希望使用每个函数来测试在向量上保留的使用或在迭代器上使用过滤器,在为每种情况编写空函数后,在运行程序时,我注意到每个函数的持续时间之间存在巨大的差异,这意味着向当前空函数添加任何逻辑都会导致对其执行时间的错误结论。

    use std::time::Instant;
    
    fn use_filter() {
        
    }
    
    fn use_retain() {
        
    }
    
    fn run_multiple(f: fn(), times: u64) {
        for _ in 0..times {
            f()
        }
    } 
    
    fn main() {
        let iter_count: u32 = 1_000_000_000;
        
        let _start_1 = Instant::now();
        run_multiple(use_filter, iter_count as u64);
        let duration = Instant::now() - _start_1;
        println!("Use Filter duration: {:?}", duration / iter_count);
        
        let _start_2 = Instant::now();
        run_multiple(use_retain, iter_count as u64);
        let duration = Instant::now() - _start_2;
        println!("Use Retain duration: {:?}", duration / iter_count);
    }
    

    预期产量

    Use Filter duration: xns
    Use Retain duration: xns
    

    其中x对于两个函数都是相同的,因为它们都是空的,什么也不做

    实际产量

    Use Filter duration: 8ns
    Use Retain duration: 10ns
    

    这可以解释为什么在rust编程语言中空函数的执行时间非常不同。

    1 回复  |  直到 6 月前
        1
  •  3
  •   user2722968    6 月前

    问题中给出的结果完全是由于噪声造成的,没有任何有用的信息。代码编译下来的内容是

        movq    std::time::Instant::now@GOTPCREL(%rip), %r14
        callq   *%r14       // First call to `Instant::now()`
        movq    %rax, %rbx
                            // `use_filter` went away entirely, as one would expect
        movl    %edx, %ebp
        callq   *%r14       // Second call to `Instand::now()`
        movq    %rax, %rdi
        movl    %edx, %esi
        movq    %rbx, %rdx
        movl    %ebp, %ecx
        callq   *<std::time::Instant as core::ops::arith::Sub>::sub@GOTPCREL(%rip)
                            // [...] print result
        callq   *%r14       // Third call to `Instant::now()`
        movq    %rax, %rbx
                            // `use_retention` went away entirely
        movl    %edx, %ebp
        callq   *%r14       // Third call to `Instant::now()`
        movq    %rax, %rdi
        movl    %edx, %esi
        movq    %rbx, %rdx
        movl    %ebp, %ecx
        callq   *<std::time::Instant as core::ops::arith::Sub>::sub@GOTPCREL(%rip)
                            // [...] print result
    

    也就是说,你的时差 测量 是向发出这两个电话所花费的时间吗 Instant::now() ,与 没有什么 在两者之间。没有区别。你的时差 看到 是由于实施过程中的不准确造成的 Instant::now() 、线程调度或一般噪声。