1 |
#!/usr/bin/perl |
2 |
|
3 |
# ->resume is not exactly cheap (it saves/restores a LOT |
4 |
# of global variables), but shouldn't be slow. just to show |
5 |
# how fast it is, this little proggie compares a normal subroutine |
6 |
# call with two calls of transfer in a loop. |
7 |
|
8 |
use Coro; |
9 |
use Benchmark; |
10 |
|
11 |
$a = bless {}, main::; |
12 |
|
13 |
# do something similar, switch two global vars and return something |
14 |
|
15 |
sub a { |
16 |
$old = $current; |
17 |
$current = $_[0]; |
18 |
} |
19 |
|
20 |
$b = new Coro sub { |
21 |
# do a little unrolling... |
22 |
while() { |
23 |
$Coro::main->resume; $Coro::main->resume; $Coro::main->resume; |
24 |
} |
25 |
}; |
26 |
|
27 |
$b->resume; # the first resume is slow because it allocates all the memory |
28 |
|
29 |
$main = $Coro::main; |
30 |
|
31 |
sub transfer { |
32 |
Coro::_transfer($_[0], $_[1]); |
33 |
} |
34 |
|
35 |
$c = Coro::_newprocess { |
36 |
while() { |
37 |
transfer($c, $main); transfer($c, $main); transfer($c, $main); |
38 |
} |
39 |
}; |
40 |
|
41 |
transfer($main, $c); |
42 |
|
43 |
timethese 100000, { |
44 |
method => '$a->a; $a->a; $a->a; $a->a', |
45 |
resume => '$b->resume; $b->resume', |
46 |
transfer => 'transfer($main, $c); transfer($main, $c)', |
47 |
}; |