使用perl准确计时执行系统调用

时间:2011-01-21 23:09:02

标签: perl

是否有更好的方法以编程方式使用perl来跟踪unix进程的时间(开始时间,结束时间)??

例如,我有一个perl脚本,它使用system()启动unix命令。我在system()之前和之后打印时间戳。

我的开始时间和结束时间的日志是相同的。我确信当这个过程完成了几分钟,所以它不准确。

到目前为止,这是我的代码:

my $dt  = strftime('%Y%m%d', localtime(time));
my $dt2 = strftime('%Y%m%d-%H:%M:%S', localtime(time)); 
my @tbls = qx(mysql -u foo -pmypw --database $dbsrc -h $node -ss -e "show tables");

open (CRLOG, ">dump-$dt.log") || die "cannot append";
foreach my $tbls (@tbls)
{
   chomp $tbls;
   print CRLOG "TIME START => $dt2\n";
   my $crfile = qq{mysql -u foo -pmypw --database $dbsrc -h $node.test.com -ss -e "SELECT 'a','b','c' UNION SELECT 1,2,3 FROM $tbls"| tr "\t" ",">$node-$tbls.$dt.csv};   system($crfile); 
   print CRLOG "COMMAND => $crfile\n";
   print CRLOG "TIME END => $dt2\n";
}; 
close (CRLOG);

2 个答案:

答案 0 :(得分:2)

$dt2是一个常量,但看起来你希望它在每次使用时重新计算时间戳。为此,您应该使用一个函数。

sub dt2 {
    return strftime('%Y%m%d-%H:%M:%S', localtime(time))
}

...

open (CRLOG, ">dump-$dt.log") || die "cannot append";
foreach my $tbls (@tbls)
{
   chomp $tbls;
   print CRLOG "TIME START => ", &dt2, "\n";
   my $crfile = qq{mysql -u foo -pmypw ...};
   system($crfile); 
   print CRLOG "COMMAND => $crfile\n";
   print CRLOG "TIME END => ", &dt2, "\n";
}; 
close (CRLOG);

答案 1 :(得分:0)

您是否尝试过使用“time”命令来执行命令?

http://www.computerhope.com/unix/utime.htm

所以在你的perl脚本中,捕获输出会是这样的:

$time_me = `/usr/bin/time $my_command`;

然后解析$ time_me变量以获取值。