登录
首页 >  Golang >  Go问答

为何 Rust 的 --release 构建速度比 Go 慢?

来源:stackoverflow

时间:2024-02-06 17:36:22 264浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《为何 Rust 的 --release 构建速度比 Go 慢?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在尝试了解 rust 的并发性和并行计算,并编写了一个小脚本,该脚本迭代向量的向量,就像它是图像的像素一样。因为一开始我试图看看 iterpar_iter 相比要快多少,所以我加入了一个基本计时器 - 这可能不是非常准确。然而,我得到了疯狂的高数字。因此,我想我应该在 go 上编写一段类似的代码,以实现轻松并发,并且性能快约 585%

rust 已使用 --release 进行测试

我也尝试过使用本机线程池,但结果是相同的。看看我使用了多少线程,我也搞了一下,但没有成功。

我做错了什么? (不要介意创建随机值填充向量向量的绝对不高效的方法)

rust 代码(~140ms)

use rand::rng;
use std::time::instant;
use rayon::prelude::*;

fn normalise(value: u16, min: u16, max: u16) -> f32 {
    (value - min) as f32 / (max - min) as f32
}

fn main() {
    let pixel_size = 9_000_000;
    let fake_image: vec> = (0..pixel_size).map(|_| {
        (0..4).map(|_| {
            rand::thread_rng().gen_range(0..=u16::max)
        }).collect()
    }).collect();

    // time starts now.
    let now = instant::now();

    let chunk_size = 300_000;

    let _normalised_image: vec>> = fake_image.par_chunks(chunk_size).map(|chunk| {
        let normalised_chunk: vec> = chunk.iter().map(|i| {
            let r = normalise(i[0], 0, u16::max);
            let g = normalise(i[1], 0, u16::max);
            let b = normalise(i[2], 0, u16::max);
            let a = normalise(i[3], 0, u16::max);
            
            vec![r, g, b, a]
        }).collect();

        normalised_chunk
    }).collect();

    // timer ends.
    let elapsed = now.elapsed();
    println!("time elapsed: {:.2?}", elapsed);
}

执行代码(~24ms)

package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

func normalise(value uint16, min uint16, max uint16) float32 {
    return float32(value-min) / float32(max-min)
}

func main() {
    const pixelSize = 9000000
    var fakeImage [][]uint16

    // Create a new random number generator
    src := rand.NewSource(time.Now().UnixNano())
    rng := rand.New(src)

    for i := 0; i < pixelSize; i++ {
        var pixel []uint16
        for j := 0; j < 4; j++ {
            pixel = append(pixel, uint16(rng.Intn(1<<16)))
        }
        fakeImage = append(fakeImage, pixel)
    }

    normalised_image := make([][4]float32, pixelSize)
    var wg sync.WaitGroup

    // Time starts now
    now := time.Now()
    chunkSize := 300_000
    numChunks := pixelSize / chunkSize
    if pixelSize%chunkSize != 0 {
        numChunks++
    }

    for i := 0; i < numChunks; i++ {
        wg.Add(1)

        go func(i int) {
            // Loop through the pixels in the chunk
            for j := i * chunkSize; j < (i+1)*chunkSize && j < pixelSize; j++ {
                // Normalise the pixel values
                _r := normalise(fakeImage[j][0], 0, ^uint16(0))
                _g := normalise(fakeImage[j][1], 0, ^uint16(0))
                _b := normalise(fakeImage[j][2], 0, ^uint16(0))
                _a := normalise(fakeImage[j][3], 0, ^uint16(0))

                // Set the pixel values
                normalised_image[j][0] = _r
                normalised_image[j][1] = _g
                normalised_image[j][2] = _b
                normalised_image[j][3] = _a
            }

            wg.Done()
        }(i)
    }

    wg.Wait()

    elapsed := time.Since(now)
    fmt.Println("Time taken:", elapsed)
}

正确答案


加快 rust 代码速度最重要的初始更改是使用正确的类型。在 go 中,您使用 [4]float32 来表示 rbga 四元组,而在 rust 中,您使用 vec。用于性能的正确类型是 [f32; 4],这是一个已知恰好包含 4 个浮点数的数组。已知大小的数组不需要进行堆分配,而 vec 始终进行堆分配。这会极大地提高您的性能 - 在我的机器上,这是 8 倍的差异。

原始片段:

    let fake_image: vec> = (0..pixel_size).map(|_| {
        (0..4).map(|_| {
            rand::thread_rng().gen_range(0..=u16::max)
        }).collect()
    }).collect();

... 

    let _normalised_image: vec>> = fake_image.par_chunks(chunk_size).map(|chunk| {
        let normalised_chunk: vec> = chunk.iter().map(|i| {
            let r = normalise(i[0], 0, u16::max);
            let g = normalise(i[1], 0, u16::max);
            let b = normalise(i[2], 0, u16::max);
            let a = normalise(i[3], 0, u16::max);
            
            vec![r, g, b, a]
        }).collect();

        normalised_chunk
    }).collect();

新片段:

    let fake_image: vec<[u16; 4]> = (0..pixel_size).map(|_| {
    let mut result: [u16; 4] = default::default();
    result.fill_with(|| rand::thread_rng().gen_range(0..=u16::max));
    result
    }).collect();

...

    let _normalised_image: vec> = fake_image.par_chunks(chunk_size).map(|chunk| {
        let normalised_chunk: vec<[f32; 4]> = chunk.iter().map(|i| {
            let r = normalise(i[0], 0, u16::max);
            let g = normalise(i[1], 0, u16::max);
            let b = normalise(i[2], 0, u16::max);
            let a = normalise(i[3], 0, u16::max);
            
            [r, g, b, a]
        }).collect();

        normalised_chunk
    }).collect();

在我的机器上,这导致大约 7.7 倍的加速,使 rust 和 go 大致持平。为每个四元组进行堆分配的开销极大地减慢了 rust 的速度,并淹没了其他所有内容;消除这一点可以让 rust 和 go 处于更平衡的地位。

其次,您的 go 代码中有一个小错误。在 rust 代码中,您计算​​归一化的 rgba,而在 go 代码中,您仅计算 _r_g_bzqbendczq b.我的机器上没有安装 go,但我想这让 go 比 rust 具有轻微的不公平优势,因为你所做的工作更少。

第三,你在 rust 和 go 中仍然没有做同样的事情。在 rust 中,您将原始图像分割成块,并为每个块生成一个 vec<[f32; 4]>。这意味着内存中仍然有一堆块,稍后您必须将它们组合成单个最终图像。在 go 中,您可以分割原始块,并将每个块写入一个公共数组中。我们可以进一步重写您的 rust 代码以完美模仿 go 代码。这是 rust 中的样子:

let _normalized_image: vec<[f32; 4]> = {
    let mut destination = vec![[0 as f32; 4]; pixel_size];
    
    fake_image
        .par_chunks(chunk_size)
        // the "zip" function allows us to iterate over a chunk of the input 
        // array together with a chunk of the destination array.
        .zip(destination.par_chunks_mut(chunk_size))
        .for_each(|(i_chunk, d_chunk)| {
        // sanity check: the chunks should be of equal length.
        assert!(i_chunk.len() == d_chunk.len());
        for (i, d) in i_chunk.iter().zip(d_chunk) {
            let r = normalise(i[0], 0, u16::max);
            let g = normalise(i[1], 0, u16::max);
            let b = normalise(i[2], 0, u16::max);
            let a = normalise(i[3], 0, u16::max);
            
            *d = [r, g, b, a];

            // alternately, we could do the following loop:
            // for j in 0..4 {
            //  d[j] = normalise(i[j], 0, u16::max);
            // }
        }
    });
    destination
};

现在,您的 rust 代码和 go 代码确实在做同样的事情。我怀疑您会发现 rust 代码稍微快一些。

最后,如果您在现实生活中这样做,您应该尝试的第一件事是使用 map,如下所示:

    let _normalized_image = fake_image.par_iter().map(|&[r, b, g, a]| {
    [ normalise(r, 0, u16::max),
      normalise(b, 0, u16::max),
      normalise(g, 0, u16::max),
      normalise(a, 0, u16::max),
      ]
    }).collect::>();

这与在我的机器上手动分块一样快。

use rand::Rng;
use std::time::Instant;
use rayon::prelude::*;

fn normalise(value: u16, min: u16, max: u16) -> f32 {
    (value - min) as f32 / (max - min) as f32
}

type PixelU16 = (u16, u16, u16, u16);
type PixelF32 = (f32, f32, f32, f32);

fn main() {
    let pixel_size = 9_000_000;
    let fake_image: Vec = (0..pixel_size).map(|_| {
        let mut rng =
            rand::thread_rng();
        (rng.gen_range(0..=u16::MAX), rng.gen_range(0..=u16::MAX), rng.gen_range(0..=u16::MAX), rng.gen_range(0..=u16::MAX))
    }).collect();

    // Time starts now.
    let now = Instant::now();

    let chunk_size = 300_000;

    let _normalised_image: Vec> = fake_image.par_chunks(chunk_size).map(|chunk| {
        let normalised_chunk: Vec = chunk.iter().map(|i| {
            let r = normalise(i.0, 0, u16::MAX);
            let g = normalise(i.1, 0, u16::MAX);
            let b = normalise(i.2, 0, u16::MAX);
            let a = normalise(i.3, 0, u16::MAX);

            (r, g, b, a)
        }).collect::>();

        normalised_chunk
    }).collect();

    // Timer ends.
    let elapsed = now.elapsed();
    println!("Time elapsed: {:.2?}", elapsed);
}

我已将使用数组切换为元组,并且该解决方案已经比您在我的计算机上提供的解决方案快了 10 倍。通过削减 vec 并使用 arc>> 或某些 mpsc 通道(通过减少堆分配量)甚至可以提高速度。

到这里,我们也就讲完了《为何 Rust 的 --release 构建速度比 Go 慢?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>