How can I get the CPU time for a perl system call?

后端 未结 3 1883
梦毁少年i
梦毁少年i 2021-01-22 20:00

I have a perl script that calls external executables using system(). I would like to measure the CPU seconds taken by these external programs. Ideally, I would like

相关标签:
3条回答
  • 2021-01-22 20:28

    You can use Capture::Tiny to capture the STDOUT and STDERR of pretty much anything in Perl.

    use Capture::Tiny 'capture';
    
    my ($stdout, $stderr, $exit) = capture { system "time ls" };
    
    print $stderr;
    

    For some reason the output is missing some whitespace on my system, but is clear enough to parse out what you need.

    0.00user 0.00system 0:00.00elapsed 0%CPU (0avgtext+0avgdata 2272maxresident)k
    0inputs+8outputs (0major+111minor)pagefaults 0swaps
    
    0 讨论(0)
  • 2021-01-22 20:41
    $ time ( ls ) 2> er ## works
    $ perl -e 'system("time (ls)")'
    sh: 1: Syntax error: word unexpected (expecting ")")
    

    The problem is that in first case, your shell is probably /bin/bash whereas in second case it is /bin/sh. If you want to run your command with another shell, you could use system LIST form:

    system("/bin/bash", "-c", "time(ls)")
    

    Note 1: There's PERL5SHELL environmnet value, but that seems to take effect only on Win32.

    Note 2: If you want to measure CPU time of child process, you could use Unix::Getrusage or BSD::Resource modules.

    0 讨论(0)
  • 2021-01-22 20:52

    You've tested the command with bash, but you passed it to sh.

    system("time (ls)")
    

    is short for

    system("/bin/sh", "-c", "time (ls)")
    

    but you want

    system("/bin/bash", "-c", "time (ls)")
    
    0 讨论(0)
提交回复
热议问题