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
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
$ 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.
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)")