Jerome Laliag
Jerome Laliag

Reputation: 47

How do I get the execution time of a Perl program?

How can I get execution time if I stop it? Example I run my perl script and I press terminal shortcut CTRL+C or CTRL+Z to stop it, then post the execution time. This is posible or not?

Upvotes: 1

Views: 4201

Answers (2)

Sobrique
Sobrique

Reputation: 53478

Perl has a built in variable called: $^T which is start time of the program.

Note - on Unix CTRL-Z stops a process (SIGSTP) (which can be continued) where CTRL-C causes it to exit. (SIGINT)

Adding a handler for SIGINT would be something like this.

$SIG{'INT'} = sub { warn "Start time: $^T\n, Run time:".( time() - $^T)."\n" };

Note - this won't actually bomb out your program any more - if you're doing this, you should probably die as well, otherwise the program will do something unexpected (e.g. not exit on a Ctrl-C - but that's ok, if it's aborting a 'current operation')

So normally you'd hook one of the other signals, like SIGUSR1 or SIGUSR2 which are explicitly for user-defined functionality. (You can then kill -USR1 <pid>)

#!/usr/bin/env perl
use strict;
use warnings;

$SIG{'INT'} = sub { warn "Started at $^T, runtime ".(time() - $^T)."\n"; die };
$SIG{'USR1'} = sub { warn "Started at $^T, runtime ".(time() - $^T)."\n"; 
                     warn "Program continuing\n"; };

while ( 1 ) {
    sleep 1;
}

Upvotes: 4

simbabque
simbabque

Reputation: 54323

On Linux, you can use the program time to get the execution time. Just prepend it to your Perl script like this.

$ cat foo.pl
1 while 1;
$ time perl foo.pl
^C
real    0m1.006s
user    0m0.756s
sys 0m0.008s

Of course this is not limited to Perl programs. It works for any program.

Upvotes: 8

Related Questions