Integrate Memoize 0.64. Few tweaks were required in
[p5sagit/p5-mst-13.2.git] / lib / Memoize / t / speed.t
1 #!/usr/bin/perl
2
3 use lib '..';
4 use Memoize;
5
6 if (-e '.fast') {
7   print "1..0\n";
8   exit 0;
9 }
10
11 print  "# Warning: I'm testing the speedup.  This might take up to sixty seconds.\n";
12
13 print "1..6\n";
14
15 sub fib {
16   my $n = shift;
17   $COUNT++;
18   return $n if $n < 2;
19   fib($n-1) + fib($n-2);
20 }
21
22 $N = 0;
23
24 $ELAPSED = 0;
25 until ($ELAPSED > 10) {
26   $N++;
27   my $start = time;
28   $COUNT=0;
29   $RESULT = fib($N);
30   $ELAPSED = time - $start;
31   print "# fib($N) took $ELAPSED seconds.\n" if $N % 1 == 0;
32 }
33
34 print "# OK, fib($N) was slow enough; it took $ELAPSED seconds.\n";
35
36
37 &memoize('fib');
38
39 $COUNT=0;
40 $start = time;
41 $RESULT2 = fib($N);
42 $ELAPSED2 = time - $start + .001; # prevent division by 0 errors
43
44 print (($RESULT == $RESULT2) ? "ok 1\n" : "not ok 1\n");
45 # If it's not ten times as fast, something is seriously wrong.
46 print (($ELAPSED/$ELAPSED2 > 10) ? "ok 2\n" : "not ok 2\n");
47 # If it called the function more than $N times, it wasn't memoized properly
48 print (($COUNT > $N) ? "ok 3\n" : "not ok 3\n");
49
50 # Do it again. Should be even faster this time.
51 $start = time;
52 $RESULT2 = fib($N);
53 $ELAPSED2 = time - $start + .001; # prevent division by 0 errors
54
55
56 print (($RESULT == $RESULT2) ? "ok 4\n" : "not ok 4\n");
57 print (($ELAPSED/$ELAPSED2 > 10) ? "ok 5\n" : "not ok 5\n");
58 # This time it shouldn't have called the function at all.
59 print ($COUNT ? "ok 6\n" : "not ok 6\n");