This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
24374cd244d36c87495c0f2a580a8245bcafd631
[perl5.git] / cpan / Time-HiRes / t / itimer.t
1 use strict;
2
3 sub has_symbol {
4     my $symbol = shift;
5     eval "use Time::HiRes qw($symbol)";
6     return 0 unless $@ eq '';
7     eval "my \$a = $symbol";
8     return $@ eq '';
9 }
10
11 use Config;
12
13 BEGIN {
14     require Time::HiRes;
15     unless(defined &Time::HiRes::setitimer
16             && defined &Time::HiRes::getitimer
17             && has_symbol('ITIMER_VIRTUAL')
18             && $Config{sig_name} =~ m/\bVTALRM\b/
19             && $^O ne 'nto' # nto: QNX 6 has the API but no implementation
20             && $^O ne 'haiku' # haiku: has the API but no implementation
21             && $^O ne 'gnu' # GNU/Hurd: has the API but no implementation
22     ) {
23         require Test::More;
24         Test::More::plan(skip_all => "no itimer");
25     }
26 }
27
28 use Test::More 0.82 tests => 2;
29 use t::Watchdog;
30
31 my $limit = 0.25; # 25% is acceptable slosh for testing timers
32
33 my $i = 3;
34 my $r = [Time::HiRes::gettimeofday()];
35
36 $SIG{VTALRM} = sub {
37     $i ? $i-- : Time::HiRes::setitimer(&Time::HiRes::ITIMER_VIRTUAL, 0);
38     note "Tick! $i ", Time::HiRes::tv_interval($r);
39 };      
40
41 note "setitimer: ", join(" ",
42     Time::HiRes::setitimer(&Time::HiRes::ITIMER_VIRTUAL, 0.5, 0.4));
43
44 # Assume interval timer granularity of $limit * 0.5 seconds.  Too bold?
45 my $virt = Time::HiRes::getitimer(&Time::HiRes::ITIMER_VIRTUAL);
46 ok defined $virt && abs($virt / 0.5) - 1 < $limit
47    or diag "virt=" . (defined $virt ? $virt : 'undef');
48
49 note "getitimer: ", join(" ",
50     Time::HiRes::getitimer(&Time::HiRes::ITIMER_VIRTUAL));
51
52 while (Time::HiRes::getitimer(&Time::HiRes::ITIMER_VIRTUAL)) {
53     my $j;
54     for (1..1000) { $j++ } # Can't be unbreakable, must test getitimer().
55 }
56
57 note "getitimer: ", join(" ",
58     Time::HiRes::getitimer(&Time::HiRes::ITIMER_VIRTUAL));
59
60 $virt = Time::HiRes::getitimer(&Time::HiRes::ITIMER_VIRTUAL);
61 note "at end, i=$i";
62 is($virt, 0, "time left should be zero");
63
64 $SIG{VTALRM} = 'DEFAULT';
65
66 1;