Created
February 17, 2017 18:54
-
-
Save netj/280d7d8ed2c0d26cac6fc4cca5ecf299 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w | |
# ts2dur -- Annotates a timestamp-per-line input with the duration between two lines | |
# | |
# Author: Jaeho Shin <[email protected]> | |
# Created: 2017-02-17 | |
## | |
use strict; | |
use POSIX qw(strftime); | |
use Date::Parse; | |
use Time::HiRes; | |
# defaults to expecting ISO8601-ish timestamp format: YYYY-mm-dd HH:MM:SS.SSSSSS | |
our $TS_FMT = $ENV{TS2DUR_TS_FORMAT} || "%Y-%m-%d %H:%M:%S.uuuuuu"; | |
our $TS_BEGIN = $ENV{TS2DUR_TS_FROM} || 0; | |
our $TS_END = $ENV{TS2DUR_TS_TO} || $TS_BEGIN + length(strftime($TS_FMT, localtime())); | |
# duration precision | |
our $PRECISION = $ENV{TS2DUR_DUR_PREC} || 10; | |
# whether duration starts at the first line or second line | |
our $DURATION_ON_THIS_LINE = $ENV{TS2DUR_DUR_AFTER} || 0; | |
my $last_ts; | |
my $last_line; | |
sub print_this_line_with_duration { | |
my $ts_str = shift; | |
my $line = shift; | |
my $ts = defined $ts_str ? str2time($ts_str) : undef; | |
if (defined $line) { | |
my $duration = defined $last_ts ? (sprintf "%0.${PRECISION}f", $ts - $last_ts) : " " x $PRECISION; | |
printf "%s\t%s", $duration, $line; | |
} | |
$last_ts = $ts; | |
} | |
sub print_last_line_with_duration { | |
my $ts_str = shift; | |
my $line = shift; | |
my $ts = defined $ts_str ? str2time($ts_str) : undef; | |
if (defined $last_line) { | |
my $duration = defined $ts ? (sprintf "%0.${PRECISION}f", $ts - $last_ts) : " " x $PRECISION; | |
printf "%s\t%s", $duration, $last_line; | |
} | |
$last_ts = $ts; | |
$last_line = $line; | |
} | |
my $print_line_with_duration = | |
$DURATION_ON_THIS_LINE ? \&print_this_line_with_duration | |
: \&print_last_line_with_duration | |
; | |
while (my $line = <>) { | |
my $ts_str = substr($line, $TS_BEGIN, $TS_END); | |
$print_line_with_duration->($ts_str, $line); | |
} | |
$print_line_with_duration->(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment