如何快速求和文件中的所有数字? [英] How can I quickly sum all numbers in a file?
问题描述
我有一个包含数千个数字的文件,每个数字都在自己的一行中:
I have a file which contains several thousand numbers, each on it's own line:
34
42
11
6
2
99
...
我想写一个脚本来打印文件中所有数字的总和.我有一个解决方案,但效率不高.(运行需要几分钟.)我正在寻找更有效的解决方案.有什么建议吗?
I'm looking to write a script which will print the sum of all numbers in the file. I've got a solution, but it's not very efficient. (It takes several minutes to run.) I'm looking for a more efficient solution. Any suggestions?
推荐答案
对于 Perl one-liner,它与 Ayman Hourieh 的回答:
For a Perl one-liner, it's basically the same thing as the awk
solution in Ayman Hourieh's answer:
% perl -nle '$sum += $_ } END { print $sum'
如果您对 Perl one-liners 的作用感到好奇,您可以解析它们:
If you're curious what Perl one-liners do, you can deparse them:
% perl -MO=Deparse -nle '$sum += $_ } END { print $sum'
结果是程序的一个更冗长的版本,以一种没人会自己编写的形式:
The result is a more verbose version of the program, in a form that no one would ever write on their own:
BEGIN { $/ = "
"; $ = "
"; }
LINE: while (defined($_ = <ARGV>)) {
chomp $_;
$sum += $_;
}
sub END {
print $sum;
}
-e syntax OK
只是为了傻笑,我用一个包含 1,000,000 个数字(在 0 - 9,999 范围内)的文件进行了尝试.在我的 Mac Pro 上,它几乎立即恢复.这太糟糕了,因为我希望使用 mmap
会非常快,但它只是在同一时间:
Just for giggles, I tried this with a file containing 1,000,000 numbers (in the range 0 - 9,999). On my Mac Pro, it returns virtually instantaneously. That's too bad, because I was hoping using mmap
would be really fast, but it's just the same time:
use 5.010;
use File::Map qw(map_file);
map_file my $map, $ARGV[0];
$sum += $1 while $map =~ m/(d+)/g;
say $sum;
这篇关于如何快速求和文件中的所有数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!