为什么排序需要这么长时间?

Mar*_*oma 4 rust

我目前正在尝试通过解决一些小任务来学习Rust的语法.如果我以正确的方式使用该语言,我将执行时间作为健全性检查进行比较.

一项任务是:

  1. 创建一个1000000随机整数的数组,范围为0 - 1000000000
  2. 对它进行排序并测量时间
  3. 打印排序时间

我得到了以下结果:

| #   | Language             | Speed  | LOCs |
| --- | -------------------- | ------ | ---- |
| 1   | C++ (with -O3)       | 1.36s  | 1    |
| 2   | Python (with PyPy)   | 3.14s  | 1    |
| 3   | Ruby                 | 5.04s  | 1    |
| 4   | Go                   | 6.17s  | 1    |
| 5   | C++                  | 7.95s  | 1    |
| 6   | Python (with Cython) | 11.51s | 1    |
| 7   | PHP                  | 36.28s | 1    |
Run Code Online (Sandbox Code Playgroud)

现在我写了以下Rust代码:

rust.rs

extern crate rand;
extern crate time;

use rand::Rng;
use time::PreciseTime;

fn main() {
    let n = 10000000;
    let mut array = Vec::new();

    let mut rng = rand::thread_rng();
    for _ in 0..n {
        //array[i] = rng.gen::<i32>();
        array.push(rng.gen::<i32>());
    }

    // Sort
    let start = PreciseTime::now();
    array.sort();
    let end = PreciseTime::now();

    println!("{} seconds for sorting {} integers.", start.to(end), n);
}
Run Code Online (Sandbox Code Playgroud)

使用以下Cargo.toml:

[package]
name = "hello_world" # the name of the package
version = "0.0.1"    # the current version, obeying semver
authors = [ "you@example.com" ]
[[bin]]
name = "rust"
path = "rust.rs"
[dependencies]
rand = "*" # Or a specific version
time = "*"
Run Code Online (Sandbox Code Playgroud)

我编译它cargo run rust.rs并运行二进制文件.它输出

PT18.207168155S seconds for sorting 10000000 integers.
Run Code Online (Sandbox Code Playgroud)

请注意,这比Python慢​​得多.我想我做错了什么.(锈和其他语言的完整源代码是在这里,如果你有兴趣.)

为什么用Rust排序需要这么长时间?我怎样才能让它更快?

Lev*_*ans 11

我在我的计算机上试过你的代码,运行它cargo run给出:

PT11.634640178S seconds for sorting 10000000 integers.
Run Code Online (Sandbox Code Playgroud)

并且cargo run --release(启用优化)给出:

PT1.004434739S seconds for sorting 10000000 integers.
Run Code Online (Sandbox Code Playgroud)

  • 我必须承认我不确切,但我的猜测是看内联函数调用.主要是比较运算符的内联. (2认同)
  • @moose"为什么优化会产生如此大的差异" - 这就是优化的重点.^ _ ^如果他们没有产生很大的不同,他们就不值得了!如果您真的很好奇,可以将代码编译到LLVM IR并检查优化和未优化之间的差异. (2认同)
  • @moose此外,`--release`标志还可以在编译器本身中完成其他性能改进,并将其应用于依赖项,例如从最终程序集中省略调试信息和源代码引用,否则会增加显着的膨胀. (2认同)