Benchmarking programs in Rust

前端 未结 8 1155
礼貌的吻别
礼貌的吻别 2020-12-07 23:50

How is it possible to benchmark programs in Rust? For example, how would I get execution time of program in seconds?

相关标签:
8条回答
  • 2020-12-08 00:50

    This answer is outdated! The time crate does not offer any advantages over std::time in regards to benchmarking. Please see the answers below for up to date information.


    You might try timing individual components within the program using the time crate.

    0 讨论(0)
  • 2020-12-08 00:50

    If you simply want to time a piece of code, you can use the time crate. time meanwhile deprecated, though. A follow-up crate is chrono.

    Add time = "*" to your Cargo.toml.

    Add

    extern crate time;
    use time::PreciseTime;
    

    before your main function and

    let start = PreciseTime::now();
    // whatever you want to do
    let end = PreciseTime::now();
    println!("{} seconds for whatever you did.", start.to(end));
    

    Complete example

    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 = "*"
    

    rust.rs

    extern crate rand;
    extern crate time;
    
    use rand::Rng;
    use time::PreciseTime;
    
    fn main() {
        // Creates an array of 10000000 random integers in the range 0 - 1000000000
        //let mut array: [i32; 10000000] = [0; 10000000];
        let n = 10000000;
        let mut array = Vec::new();
    
        // Fill the array
        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);
    }
    
    0 讨论(0)
提交回复
热议问题