-
Notifications
You must be signed in to change notification settings - Fork 3
/
range.php
85 lines (71 loc) · 1.86 KB
/
range.php
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
80
81
82
83
84
85
<?php
error_reporting(E_ALL);
function xrange($start, $end, $step = 1) {
for ($i = $start; $i < $end; $i += $step) {
yield $i;
}
}
class RangeIterator implements Iterator {
protected $start;
protected $end;
protected $step;
protected $key;
protected $value;
public function __construct($start, $end, $step = 1) {
$this->start = $start;
$this->end = $end;
$this->step = $step;
}
public function rewind() {
$this->key = 0;
$this->value = $this->start;
}
public function valid() {
return $this->value < $this->end;
}
public function next() {
$this->value += $this->step;
$this->key += 1;
}
public function current() {
return $this->value;
}
public function key() {
return $this->key;
}
}
function urange($start, $end, $step = 1) {
$result = [];
for ($i = $start; $i < $end; $i += $step) {
$result[] = $i;
}
return $result;
}
function testTraversable($name, callable $traversableFactory) {
$startTime = microtime(true);
foreach ($traversableFactory() as $value) {
// noop
}
echo $name, ' took ', microtime(true) - $startTime, ' seconds.', "\n";
}
function testVariants($count) {
testTraversable(
"xrange ($count)",
function() use($count) { return xrange(0, $count); }
);
testTraversable(
"RangeIterator ($count)",
function() use($count) { return new RangeIterator(0, $count); }
);
testTraversable(
"urange ($count)",
function() use($count) { return urange(0, $count); }
);
testTraversable(
"range ($count)",
function() use($count) { return range(0, $count); }
);
}
testVariants(1000000);
testVariants(10000);
testVariants(100);