为什么我的 rust 程序比 ruby​​ 等价的程序慢? [英] Why is my rust program slower than ruby equivalent?

查看:120
本文介绍了为什么我的 rust 程序比 ruby​​ 等价的程序慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Ruby 和 Rust 编写了一个字谜查找器,非常惊讶地发现 Rust 程序比 Ruby 版本慢了几乎 2 倍.

Ruby 版本:

source = ARGV.firstsorted_source = source.chars.sort.join字谜 = Hash.newFile.open('/usr/share/dict/words') 做 |f|f.each_line 做 |l|字 = l.chompsorted_word = word.chars.sort.join如果字谜[sorted_word]字谜[sorted_word] <<单词别的字谜[sorted_word] = [word]结尾结尾结尾found = 字谜[sorted_source]发现看跌期权

Rust 版本:

使用 std::os;使用 std::io::{File, BufferedReader};使用 std::collections::HashMap;fn 主(){let path = Path::new("/usr/share/dict/words");匹配文件::打开(&路径){错误(e) =>println!("打开文件出错:{}", e.desc),好的(f) =>{let mut anagrams: HashMap>= HashMap::new();让 mut reader = BufferedReader::new(f);对于 reader.lines() 中的 may_line {让 word = Maybe_line.unwrap().as_slice().trim_chars('\n').to_string();let mut chars: Vec= word.as_slice().chars().collect();字符排序();让 sorted_word = String::from_chars(chars.as_slice());如果 anagrams.contains_key(&sorted_word) {anagrams.get_mut(&sorted_word).push(word);} 别的 {anagrams.insert(sorted_word, vec!(word));}}让 args = os::args();如果 args.len() == 2 {让源 = args[1].clone();let mut chars: Vec= source.as_slice().chars().collect();字符排序();让 sorted_word = String::from_chars(chars.as_slice());match anagrams.find(&sorted_word) {一些(字谜)=>println!("{}", 字谜),无 =>println!("没有找到字谜")}} 别的 {println!("使用恰好 1 个参数调用应用程序,即要为其查找字谜的单词");}}}}

结果:

 时间 ruby​​ anagram.rb 马马鞋匠支撑ruby anagram.rb 马 1.69s 用户 0.12s 系统 99% cpu 1.812 总计时间 ./字谜马[马,鞋匠,岸]./anagram horse 3.02s user 0.05s system 99% cpu 3.080 total

红宝石 -v
ruby 2.1.3p242 (2014-09-19 修订版 47630) [x86_64-darwin13.0]

rustc --version
rustc 0.13.0-nightly (172b59abe 2014-10-25 00:32:07 +0000)

Ruby 要点:https://gist.github.com/Valve/533e0e22ae427d9ce440>

Rust 要点:https://gist.github.com/Valve/834917941b00668478f2>

更新:

正如 Francis Gagne 建议的那样,我用 -O 标志编译它:

 时间 ./anagram 马[马,鞋匠,岸]./anagram horse 0.37s user 0.05s system 96% cpu 0.429 total

这使速度提高了 8 倍,但仍仅比 ruby​​ 版本快 4 倍.我猜现在这是文件系统限制.

文件的大小是:我机器上的 235886 行.

解决方案

如果您使用 Cargo,您可以将优化设置为高于 -O.

在您的 Cargo.toml 中.

[包]名称 = "字谜"版本 = "0.1.0"author = ["你的名字在这里<你的电子邮件在这里>"][profile.release]选择级别 = 3

然后运行Cargo build --release.完成后运行 time ./anagram horse

I wrote an anagram finder in Ruby and Rust and was very surprised to find that Rust program is almost 2 times slower than Ruby version.

Ruby version:

source = ARGV.first
sorted_source = source.chars.sort.join
anagrams = Hash.new
File.open('/usr/share/dict/words') do |f|
  f.each_line do |l|
    word = l.chomp
    sorted_word = word.chars.sort.join
    if anagrams[sorted_word]
      anagrams[sorted_word] << word
    else
      anagrams[sorted_word] = [word]
    end
  end
end
found = anagrams[sorted_source]
puts  found

Rust version:

use std::os;
use std::io::{File, BufferedReader};
use std::collections::HashMap;
fn main(){

    let path = Path::new("/usr/share/dict/words");
    match File::open(&path) {
        Err(e) => println!("Error opening file: {}", e.desc),
        Ok(f) => {
            let mut anagrams: HashMap<String, Vec<String>> = HashMap::new();
            let mut reader = BufferedReader::new(f);
            for maybe_line in reader.lines() {
                let word = maybe_line.unwrap().as_slice().trim_chars('\n').to_string();
                let mut chars: Vec<char> = word.as_slice().chars().collect();
                chars.sort();
                let sorted_word = String::from_chars(chars.as_slice());
                if anagrams.contains_key(&sorted_word) {
                    anagrams.get_mut(&sorted_word).push(word);
                } else {
                    anagrams.insert(sorted_word, vec!(word));
                }
            }

            let args = os::args();
            if args.len() == 2 {
                let source = args[1].clone();
                let mut chars: Vec<char> = source.as_slice().chars().collect();
                chars.sort();
                let sorted_word = String::from_chars(chars.as_slice());
                match anagrams.find(&sorted_word) {
                    Some(anagrams) => println!("{}", anagrams),
                    None => println!("No anagrams found")
                }
            } else {
                println!("Call the app with exactly 1 argument, the word to find anagrams for");
            }
        }
    }
}

Results:

 time ruby anagram.rb horse                                                                                                              
horse
shoer
shore
ruby anagram.rb horse  1.69s user 0.12s system 99% cpu 1.812 total



time ./anagram horse                                                                                                                    
[horse, shoer, shore]
./anagram horse  3.02s user 0.05s system 99% cpu 3.080 total

ruby -v
ruby 2.1.3p242 (2014-09-19 revision 47630) [x86_64-darwin13.0]

rustc --version
rustc 0.13.0-nightly (172b59abe 2014-10-25 00:32:07 +0000)

Ruby gist: https://gist.github.com/Valve/533e0e22ae427d9ce440

Rust gist: https://gist.github.com/Valve/834917941b00668478f2

UPDATE:

As Francis Gagne suggested, I compiled it with -O flag:

 time ./anagram horse                                                                                                                    
[horse, shoer, shore]
./anagram horse  0.37s user 0.05s system 96% cpu 0.429 total

This did a 8x increase in speed, but still only 4x times faster than ruby version. I guess this is a file system limitation now.

The size of the file is: 235886 lines on my machine.

解决方案

If you're using Cargo you can set the optimization higher than -O.

In your Cargo.toml.

[package]
name = "anagram"
version = "0.1.0"
authors = ["Your name here <Your email here>"]

[profile.release]
opt-level = 3

And run Cargo build --release. Once that is finished run time ./anagram horse

这篇关于为什么我的 rust 程序比 ruby​​ 等价的程序慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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