Skip to content

Instantly share code, notes, and snippets.

@erantapaa
Last active August 29, 2015 14:22
Show Gist options
  • Save erantapaa/c6c4f0cdf8484e2b0048 to your computer and use it in GitHub Desktop.
Save erantapaa/c6c4f0cdf8484e2b0048 to your computer and use it in GitHub Desktop.
annotate - annotate output with time elapsed
#!/usr/bin/perl
use POSIX qw(strftime);
$| = 1;
sub annotate_handle {
my ($handle) = @_;
my $start = time();
while (<$handle>) {
my $diff = time() - $start;
my $h = int($diff / 3600);
my $m = int (($diff % 3600) / 60);
my $s = $diff % 60;
my $ts = sprintf("%02d:%02d:%02d", $h, $m, $s);
print "$ts $_";
}
}
sub spawn {
my (@args) = @_;
my ($rh, $wh);
pipe($rh, $wh);
my $pid = fork();
if (!defined($pid)) {
die "unable to fork: $!\n";
}
if ($pid) { # parent
close($wh);
return $rh;
} else {
close($rh);
open(STDOUT, ">&", $wh);
open(STDERR, ">&", $wh);
exec(@args) or die "unable to exec: $!";
}
}
sub main {
if (@ARGV) {
my $fh = spawn(@ARGV);
annotate_handle($fh);
} else {
annotate_handle(\*STDIN);
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment