Browse Source

fragments/sparkline.pl: simple histograms

I worked this out the other night before doing something similar for a
log monitoring utility we use at WMF.

It could use some improvements, and ideally it'd be a general-purpose
utility, but might as well capture this version here.
main
Brennen Bearnes 6 months ago
parent
commit
e44b970425
1 changed files with 66 additions and 0 deletions
  1. +66
    -0
      home/fragments/sparkline.pl

+ 66
- 0
home/fragments/sparkline.pl View File

@ -0,0 +1,66 @@
#!/usr/bin/env perl
use warnings;
use strict;
use 5.10.0;
use utf8;
use open ':encoding(UTF-8)';
use open qw(:std :utf8);
use Time::Piece;
use Time::Seconds;
# We're simulating Unix timestamps here:
my $end = localtime->epoch;
my $start = $end - (3600);
say "Starting at: $start";
my @bars = qw(_ ▁ ▂ ▃ ▄ ▅ ▆ ▇ █);
my $bin_count = 12;
my $range = $end - $start;
my $bin_width = $range / $bin_count;
my %bins;
for (0..($bin_count - 1)) {
my $bin_start = $start + ($_ * $bin_width);
$bins{$bin_start} = 0;
}
# Fake some events:
for (1..200) {
my $event = $start + int(rand($range));
for my $bin (keys %bins) {
if (($event > $bin) && ($event < ($bin + $bin_width))) {
$bins{$bin}++;
}
}
}
# Figure out what the tallest bin is, and map to a unit size.
my $biggest_bin = 0;
foreach my $bin_height (values %bins) {
if ($bin_height > $biggest_bin) {
$biggest_bin = $bin_height;
}
}
# Just some debugging - print bin starts and counts:
foreach my $bin (sort keys %bins) {
say $bin . " " . $bins{$bin};
}
# Display a bar for each bin:
foreach my $bin (sort keys %bins) {
my $bar_level = int(($bins{$bin} / $biggest_bin) * (scalar @bars));
my $bar = ' ';
if ($bar_level) {
$bar = $bars[$bar_level - 1];
}
print $bar;
}
print "\n";
say "Ending at: $end";

Loading…
Cancel
Save