【问题标题】:Perl performance when reading and writing the same file读取和写入同一文件时的 Perl 性能
【发布时间】:2023-03-11 14:10:01
【问题描述】:

在 Linux 上,这两种使用 Perl 读取/写入用户文件的方式之间是否存在明显的性能差异?

选项 1:

open (READFILE, '<:utf8', "users/$_[0]") or die ("no read users/$_[0]");
    # Do the reading
close (READFILE) or die;
# Do more stuff
open (WRITEFILE, '>:utf8', "users/$_[0]") or die ("no write users/$_[0]"); flock (WRITEFILE, 2) or die ("no lock users/$_[0]");
    # Do the writing
close (WRITEFILE) or die;

选项 2:

open (USERFILE, '+<:utf8', "users/$_[0]") or die ("no open users/$_[0]"); flock (USERFILE, 2) or die ("no lock users/$_[0]");
    # Do the reading
    # Do more stuff
    seek (USERFILE, 0, 0); truncate (USERFILE, 0);
    # Do the writing
close (USERFILE) or die ("no write users/$_[0]");

用户文件不大,通常为 20-40 行或每个 2-4 KB。

还有其他理由选择选项 1 或 2(或第 3 个选项)吗?

【问题讨论】:

  • 是什么阻碍了您进行测试和测量?
  • @Hynek -Pichi- Vychodil,你说得有道理。将在未来进行基准测试。

标签: perl file-io


【解决方案1】:

这是一个你可以用来测试它的基准,我怀疑如果你先close,然后再open,获取一个新的文件描述符会花费更长的时间。

#!/usr/bin/env perl

use warnings;
use strict;
use open qw(:encoding(utf8) :std);

use Benchmark qw<cmpthese>;
my $text = <<TEXT;
I had some longer text here, but for better readability, just
these two lines.
TEXT


cmpthese(10_000,{
     close => sub{
       open my $file, '<',"bla" or die "$!";
       my @array = <$file>;
       close $file or die;
       open $file, '>',"bla" or die "$!";
       $file->print($text)
     },
     truncate => sub {
       open my $file, '+<',"bla" or die "$!";
       my @array = <$file>;
       seek $file,0,0;
       truncate $file, 0;
       $file->print($text)
     },
     truncate_flock => sub {
       open my $file, '+<',"bla" or die "$!";
       flock $file, 2;
       my @array = <$file>;
       seek $file,0,0;
       truncate $file, 0;
       $file->print($text)
     },

});

我的机器上的输出:

                 Rate          close truncate_flock       truncate
close          2703/s             --           -15%           -17%
truncate_flock 3175/s            17%             --            -3%
truncate       3257/s            21%             3%             --

比率越高越好。使用 close 会慢 1.17 倍。 但这在很大程度上取决于您的more stuff 需要多长时间,因为您在truncate 示例中使用flocking 文件,并且如果另一个程序试图访问该文件,它可能会因此而变慢。

【讨论】:

  • use 5.01; 在技术上是正确的,但会误导读者认为您需要 Perl 5.1。 use v5.10; 更清晰。如果你对 v 格式有些反感(向后兼容非常老的 Perls?)至少要说 use 5.010;
  • @Schwern:实际上我更喜欢v5.10 变体,但我不喜欢这个警告。在这种情况下,我实际上不确定是否需要它,所以我将其删除。
  • 我很少在 5.010 的机器上工作,并且有一个兼容性警告,但它们最近更新了。
  • 感谢您为我做基准测试。除非有人添加具有更多见解的答案,否则我会在这些天接受此答案。
猜你喜欢
  • 1970-01-01
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
相关资源
最近更新 更多