Debian Codegraph @

cassandane/Cassandane/Util/Metronome.pm

raw
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 2011-2017 FastMail Pty Ltd. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # 3. The name "Fastmail Pty Ltd" must not be used to
18 # endorse or promote products derived from this software without
19 # prior written permission. For permission or any legal
20 # details, please contact
21 # FastMail Pty Ltd
22 # PO Box 234
23 # Collins St West 8007
24 # Victoria
25 # Australia
26 #
27 # 4. Redistributions of any form whatsoever must retain the following
28 # acknowledgment:
29 # "This product includes software developed by Fastmail Pty. Ltd."
30 #
31 # FASTMAIL PTY LTD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
32 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
33 # EVENT SHALL OPERA SOFTWARE AUSTRALIA BE LIABLE FOR ANY SPECIAL, INDIRECT
34 # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
35 # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
36 # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
37 # OF THIS SOFTWARE.
38 #
39
40 package Cassandane::Util::Metronome;
41 use strict;
42 use warnings;
43 use Time::HiRes qw(clock_gettime clock_nanosleep CLOCK_MONOTONIC);
44
45 use lib '.';
46 use Cassandane::Util::Log;
47
48 sub new
49 {
50 my ($class, %params) = @_;
51
52 my $self = {
53 # These are floating point numbers in seconds
54 # with presumed nanosecond resolution
55 interval => 0.0,
56 error => 0.0,
57 last_tick => undef,
58 first_tick => undef,
59 nticks => 0,
60 };
61
62 $self->{interval} = $params{interval}
63 if defined $params{interval};
64 $self->{interval} = 1.0/$params{rate}
65 if defined $params{rate};
66
67 return bless $self, $class;
68 }
69
70 sub tick
71 {
72 my ($self) = @_;
73
74 my $now = clock_gettime(CLOCK_MONOTONIC);
75 $self->{first_tick} ||= $now;
76 $self->{nticks}++;
77 my $next_tick = ($self->{last_tick} || $now)
78 + $self->{interval};
79 my $delay = ($next_tick + $self->{error} - $now);
80 clock_nanosleep(CLOCK_MONOTONIC, 1e9 * $delay)
81 if ($delay > 0.0);
82 $now = clock_gettime(CLOCK_MONOTONIC);
83 $self->{error} = $next_tick - $now;
84 $self->{last_tick} = $next_tick;
85 }
86
87 sub actual_rate
88 {
89 my ($self) = @_;
90
91 return undef if !$self->{nticks};
92 return $self->{nticks} /
93 (clock_gettime(CLOCK_MONOTONIC) - $self->{first_tick});
94 }
95
96 1;