-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfor_loop_versus_sum.py
More file actions
48 lines (32 loc) · 1.1 KB
/
for_loop_versus_sum.py
File metadata and controls
48 lines (32 loc) · 1.1 KB
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
#!/usr/bin/env python
# pylint: disable=C0103
"""Compare 'for loop' performance versus 'sum' performance."""
import gc
import benchmark
class Benchmark_For_loop(benchmark.Benchmark):
"""Benchmark 'for loop'."""
each = 1000 # allows for differing number of runs
def setUp(self):
"""Define the number of benchmarks to perform."""
self.size = 25000
def test_for_loop(self):
"""Sum with a 'for' loop."""
total = 0
for i in xrange(self.size):
total += i
assert total == 312487500
return total
class Benchmark_Sum_with_xrange(benchmark.Benchmark):
"""Benchmark 'for loop'."""
each = 1000 # allows for differing number of runs
def setUp(self):
"""Define the number of benchmarks to perform."""
self.size = 25000
def test_sum_with_xrange(self):
"""Sum with built-in sum and range."""
total = sum(xrange(self.size))
assert total == 312487500
return total
if __name__ == '__main__':
gc.disable()
benchmark.main(each=50000, format="markdown", numberFormat="%.4g")