File: timeq

package info (click to toggle)
trend 1.2-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 220 kB
  • ctags: 283
  • sloc: cpp: 1,891; perl: 110; makefile: 50; sh: 12
file content (79 lines) | stat: -rwxr-xr-x 1,294 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env perl
# a very basic and imprecise time quantizer

use strict;
use warnings;
use Getopt::Std qw{getopts};
use Time::HiRes qw{usleep gettimeofday tv_interval};

# be sure to flush right away!
$| = 1;

# arguments
my %flags;
getopts('s', \%flags);
my $ms = ($ARGV[0]? $ARGV[0]: 1);
my $dlen = length(pack("d", ()));

# parser 
sub parser()
{
  while(<STDIN>)
  {
    my $v = pack("d", ($_ + 0));
    syswrite(FD, $v, $dlen);
  }
}

# quantizer
sub quantize()
{
  my $res = $ms;
  my $cum = 0;
  my $num = 0;

  # prepare fds
  my $fds = '';
  vec($fds, fileno(STDIN), 1) = 1;

  while($fds)
  {
    # select
    my $pre = [gettimeofday];
    my $rfs = $fds;
    my $n = select($rfs, undef, undef, $res);
    $res -= tv_interval($pre, [gettimeofday]);

    # return values
    if($n > 0)
    {
      my $v;
      if(!sysread(STDIN, $v, $dlen)) {
	$fds = undef;
      } else {
	++$num;
	$cum += unpack("d", $v);
      }
    }

    # average
    if($res <= 0)
    {
      my $v = ($flags{s}? $cum: ($num? $cum / $num: 0));
      syswrite(STDOUT, pack("d", $v), $dlen);

      # we should rather compensate than drift
      $num = $cum = 0;
      $res += $ms;
    }
  }
}

# execution
my $pid = open(FD, "|-");
die unless(defined($pid));
if($pid) {
  parser();
} else {
  quantize();
}