- 论坛徽章:
- 0
|
首先用ruby产生一个充满随机数的文件,共500万行,每行7列。
- x = Random.new
- f = File.open("500w.txt","w")
- 5000000.times do |c|
- str = ''
- 7.times do |d|
- str << x.rand(10000..99999).to_s + " "
- end
- f.puts str
- end
复制代码
执行完后获得500w.txt文件,耗时1分16秒:
$ time ruby random.rb
real 1m16.227s
user 1m14.022s
sys 0m1.391s
该文件大小和长度:
$ wc -l 500w.txt
5000000 500w.txt
$ du -h 500w.txt
206M 500w.txt
然后编写一个stat.rb脚本,和一个stat.pl脚本,统计第6列的唯一出现次数。
ruby脚本如下:
- hash = Hash.new(0)
- File.open("500w.txt").each do |c|
- hash[$2] +=1 if c =~ /^(\S+\s+){5}(\S+)/
- end
- puts hash.keys.size
复制代码
perl脚本如下:
- use strict;
- my %hash;
- open my $fd,"500w.txt" or die $!;
- while(<$fd>) {
- $hash{$2} ++ if /^(\S+\s+){5}(\S+)/;
- }
- close $fd;
- print scalar keys %hash;
复制代码
执行ruby脚本:
$ time ruby stat.rb
90000
real 0m29.532s
user 0m29.343s
sys 0m0.163s
执行perl脚本:
$ time perl stat.pl
90000
real 0m19.755s
user 0m19.518s
sys 0m0.229s
ruby的版本:
perl的版本:
$ perl -v
This is perl, v5.8.8 built for i686-linux
CPU:Xeon CPU 2.8G,多少核不用管了,反正用不着。
内存:物理内存2G,执行过程中未用到交换内存。
总结:ruby比perl慢了1/3。这取决于几方面:
(1)I/O的效率。
(2)Hash的效率。
(3)正则表达式的效率。
结合邮件列表上曾经的相关讨论可认为,是Perl的正则表达式执行效率完全胜出! |
|