为什么计时器显示的内容如此违反直觉? [英] Why is what timers show so counter-intuitive?

查看:64
本文介绍了为什么计时器显示的内容如此违反直觉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一些文本的解析器.我需要支持 unicode 文本,这就是我使用 String::chars 迭代器的原因:

I am making a parser of some text. I need to support unicode texts, that's why I am using the String::chars iterator:

游乐场

use std::time::Instant;

fn main() {
    let text = "a".repeat(10000);
    let mut timer1 = 0;
    let mut timer2 = 0;

    let start1 = Instant::now();
    for pos in 1..10000 {
        let start2 = Instant::now();
        let ch = text.chars().nth(pos).unwrap();
        timer2 += start2.elapsed().as_millis();
    }
    timer1 += start1.elapsed().as_millis();

    println!("timer1: {} timer2: {}", timer1, timer2);
}

示例输出:

timer1: 4276 timer2: 133

为什么 timer2 难以置信地小于 timer1,而我认为它们应该彼此非常接近?

Why is timer2 unbelievably less than timer1, when I believe they should be very close to each other?

附言我已经知道 .nth 很慢,不应该使用.

P.S. I know already that .nth is slow, and shouldn't be used.

推荐答案

您遇到了解决问题.循环内部的执行时间(平均)不到一毫秒,所以 start2.elapsed().as_millis() 通常评估为 0.要解决这个问题,你可以在里面做一些操作需要更长时间的循环,或者将分辨率从毫秒更改为更小的值,例如微秒或纳秒.

You are running into a resolution problem. The inside of the loop takes (on average) less than one millisecond to execute, so start2.elapsed().as_millis() usually evaluates to 0. To fix this problem, you could do some operation inside the loop that takes even longer, or change your resolution from milliseconds to something smaller, like microseconds or nanoseconds.

切换到微秒会产生更一致的时间

switching to microseconds yields a more consistent time

use std::time::{Instant};

fn main() {
    let text = "a".repeat(10000);
    let mut timer1 = 0;
    let mut timer2 = 0;

    let start1 = Instant::now();
    for pos in 1..10000 {
        let start2 = Instant::now();
        let ch = text.chars().nth(pos).unwrap();
        timer2+=start2.elapsed().as_micros();
    }
    timer1+=start1.elapsed().as_micros();

    println!("timer1: {} timer2: {}", timer1, timer2);
}

输出

timer1: 3511812 timer2: 3499669

这个问题被标记为性能,所以我想指出使用 std::Instant 是一种非常乏味的衡量性能的方法.更好的方法包括 criterion.rs火焰图载货台.

This question was tagged performance, so I'd like to point out that using std::Instant is a very tedious way to measure performance. Better ways include criterion.rs, flamegraph and cargo-bench.

这篇关于为什么计时器显示的内容如此违反直觉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆