Debian Codegraph @

tests/benchmark_scale.py

raw
1 """Benchmark SortedContainers at scale.
2
3 ## Local Results
4
5 $ pypy benchmark_scale.py --limit 1e9
6 @ Method Size Operations Time Ops/Sec Ratio
7 @ add 1e+06 1e+04 0.01501 666045.025 nan
8 @ add 1e+07 1e+05 0.26612 375764.681 1.773
9 @ add 1e+08 1e+06 4.69080 213183.298 1.763
10 @ add 1e+09 1e+07 83.01831 120455.358 1.770
11 @ del 1e+06 1e+04 0.00827 1208897.485 nan
12 @ del 1e+07 1e+05 0.13309 751393.836 1.609
13 @ del 1e+08 1e+06 3.79143 263752.866 2.849
14 @ del 1e+09 1e+07 124.59184 80262.081 3.286
15
16 ## High Memory Instance Results
17
18 Note: Requires ~128 GB of memory.
19 Note: Requires ~11 hrs to run.
20
21 $ nohup /home/grantj/PyPy27/bin/pypy benchmark_scale.py &
22 $ cat nohup.out
23 @ Method Size Ops Time Ops/Sec Ratio
24 @ add 1e+06 1e+04 0.02133 468884.826 nan
25 @ add 1e+07 1e+05 0.38629 258872.924 1.811
26 @ add 1e+08 1e+06 6.20695 161109.825 1.607
27 @ add 1e+09 1e+07 120.24735 83161.919 1.937
28 @ add 1e+10 1e+08 2416.60713 41380.330 2.010
29 @ del 1e+06 1e+04 0.01791 558289.343 nan
30 @ del 1e+07 1e+05 0.26171 382097.449 1.461
31 @ del 1e+08 1e+06 6.11150 163626.036 2.335
32 @ del 1e+09 1e+07 171.58899 58278.798 2.808
33 @ del 1e+10 1e+08 5493.95076 18201.838 3.202
34
35 ### CPU Info
36
37 Architecture: x86_64
38 CPU op-mode(s): 32-bit, 64-bit
39 Byte Order: Little Endian
40 CPU(s): 32
41 On-line CPU(s) list: 0-31
42 Thread(s) per core: 2
43 Core(s) per socket: 16
44 Socket(s): 1
45 NUMA node(s): 1
46 Vendor ID: GenuineIntel
47 CPU family: 6
48 Model: 63
49 Model name: Intel(R) Xeon(R) CPU @ 2.30GHz
50 Stepping: 0
51 CPU MHz: 2299.998
52 BogoMIPS: 4599.99
53 Hypervisor vendor: KVM
54 Virtualization type: full
55 L1d cache: 32K
56 L1i cache: 32K
57 L2 cache: 256K
58 L3 cache: 46080K
59 NUMA node0 CPU(s): 0-31
60
61 """
62 from __future__ import print_function
63
64 import argparse
65 import collections as co
66 import functools as ft
67 import gc
68 import itertools as it
69 import math
70 import random
71 import sortedcontainers as sc
72 import sys
73 import time
74
75
76 CHECK = False
77
78
79 def iter_with_description(iterable, description=''):
80 "Placeholder iterator function with ignored description parameter."
81 return iter(iterable)
82
83
84 PROGRESS = iter_with_description
85
86
87 def init_sorted_list(sl, size, moment=5, fraction=0.1):
88 """Initialize SortedList with normally distributed sublist lengths.
89
90 The mean of the normal distribution is given by:
91
92 mu = load * (1.0 + moment / 10.0)
93
94 And the standard deviation of the normal distribution is given by:
95
96 sigma = load * fraction
97
98 For a visualization of positive and negative moments see:
99
100 * plot_lengths_histogram.py
101 * plot_lengths_histogram_delitem.py
102
103 :param SortedList sl: SortedList to initialize
104 :param int size: size of the resulting SortedList
105 :param int moment: number between -5 and 9 inclusive
106 :param float fraction: fraction of load to be used as standard deviation
107 :return: initialized sorted list
108
109 """
110 assert -5 <= moment <= 9
111 assert 0 < fraction
112
113 sl.clear()
114
115 load = sl._load
116 half = sl._load >> 1
117 twice = sl._load << 1
118 mu = load * (1.0 + moment / 10.0)
119 sigma = load * fraction
120 total = 0
121
122 class WhileIterator(object):
123 "Convert for-loop to while-loop with length estimate."
124 def __iter__(self):
125 while total < size:
126 yield True
127 def __len__(self):
128 if moment < 0:
129 return size / half
130 else:
131 return size / load
132
133 for each in PROGRESS(WhileIterator(), 'init-sub'):
134 count = int(random.normalvariate(mu, sigma))
135
136 if moment >= 0:
137 if count < load:
138 count += load
139 elif count > twice:
140 count -= load
141
142 count = min(count, twice)
143 count = max(count, load)
144 else:
145 if count < half:
146 count += half
147 elif count > load:
148 count -= half
149
150 count = min(count, load)
151 count = max(count, half)
152
153 sl._lists.append(list(xrange(total, total + count)))
154 total += count
155
156 sl._len = sum(len(sublist) for sublist in sl._lists)
157 sl._maxes[:] = [sublist[-1] for sublist in sl._lists]
158
159 for each in PROGRESS(xrange(len(sl) - size), 'init-del'):
160 del sl[random.randrange(len(sl))]
161
162 del sl._index[:]
163
164 if CHECK: sl._check()
165
166 assert len(sl) == size
167
168 return sl
169
170
171 def timeit(func):
172 "Decorator to time function calls."
173 @ft.wraps(func)
174 def wrapper(*args, **kwargs):
175 "Return timed duration of function call. Ignores function result."
176 start = time.clock()
177 result = func(*args, **kwargs)
178 end = time.clock()
179 return (end - start)
180 return wrapper
181
182
183 @timeit
184 def add(obj, numbers):
185 "Repeatedly add number from numbers to sorted list."
186 for number in PROGRESS(numbers, 'add'):
187 obj.add(number)
188
189
190 @timeit
191 def delitem(obj, indices):
192 "Repeatedly delete values from sorted list by index in indices."
193 for index in PROGRESS(indices, 'del'):
194 del obj[index]
195
196
197 def randvalues(limit, fraction=0.001):
198 "Return fraction of limit random values between 0 and limit."
199 iterable = PROGRESS(xrange(int(limit * fraction)), 'randvalues')
200 return [random.randrange(limit) for each in iterable]
201
202
203 def randindices(limit, fraction=0.002):
204 "Return fraction of limit random indices counting down from limit."
205 stop = limit - int(limit * fraction)
206 iterable = PROGRESS(xrange(limit, stop, -1), 'randindices')
207 return [random.randrange(length) for length in iterable]
208
209
210 def benchmark_add(start, limit, times):
211 """Benchmark sorted list add method.
212
213 Start and limit are an inclusive range of magnitudes.
214
215 The load of the sorted list is the cube root of the size.
216
217 Measurements are made by sampling performance at each "moment" of a sorted
218 list while items are added to it. See `init_sorted_list` for how "moment"
219 is used.
220
221 """
222 for exponent in xrange(start, limit + 1):
223 timings = []
224 count = 10 ** exponent
225 sl = sc.SortedList(load=int(count ** (1.0 / 3)))
226
227 for attempt in xrange(times):
228 subtimings = []
229
230 for moment in xrange(10):
231 values = randvalues(count)
232 init_sorted_list(sl, count, moment)
233 gc.collect()
234 subtiming = add(sl, values)
235 subtimings.append(subtiming)
236
237 timing = sum(subtimings)
238 timings.append(timing)
239
240 display('add', timings, count)
241
242
243 def benchmark_del(start, limit, times):
244 """Benchmark sorted list delitem method.
245
246 Start and limit are an inclusive range of magnitudes.
247
248 The load of the sorted list is the square root of the size.
249
250 Measurements are made by sampling performance at each "moment" of a sorted
251 list while items are deleted from it. See `init_sorted_list` for how
252 "moment" is used.
253
254 """
255 for exponent in xrange(start, limit + 1):
256 timings = []
257 count = 10 ** exponent
258 sl = sc.SortedList(load=int(count ** (1.0 / 3))) # 2)))
259
260 for attempt in xrange(times):
261 subtimings = []
262
263 for moment in xrange(-5, 0):
264 indices = randindices(count)
265 init_sorted_list(sl, count, moment)
266 gc.collect()
267 subtiming = delitem(sl, indices)
268 subtimings.append(subtiming)
269
270 timing = sum(subtimings)
271 timings.append(timing)
272
273 display('del', timings, count)
274
275
276 def display(name, times, size, last=['', 0]):
277 "Display performance summary with ratio of ops/sec."
278
279 times.sort()
280 median_time = times[len(times) / 2]
281 operations = size / 100
282 ops_sec = operations / median_time
283
284 last_name, last_ops_sec = last
285 ratio = last_ops_sec / ops_sec if name == last_name else float('nan')
286 last[0], last[1] = name, ops_sec
287
288 template = '@%9s %.0e %.0e %14.5f %12.3f %6.3f'
289 print(template % (name, size, operations, median_time, ops_sec, ratio))
290 sys.stdout.flush()
291
292
293 if __name__ == '__main__':
294 parser = argparse.ArgumentParser()
295 parser.add_argument('--start', default=1e6, type=float)
296 parser.add_argument('--limit', default=1e10, type=float)
297 parser.add_argument('--seed', default=0, type=int)
298 parser.add_argument('--times', default=5, type=int)
299 parser.add_argument('--funcs', default='all', choices=['all', 'add', 'del'])
300 parser.add_argument('--progress', action='store_true')
301 parser.add_argument('--check', action='store_true')
302
303 args = parser.parse_args()
304
305 random.seed(args.seed)
306
307 if args.progress:
308 import tqdm
309 PROGRESS = tqdm.tqdm
310
311 CHECK = args.check
312
313 start = int(math.log10(args.start))
314 limit = int(math.log10(args.limit))
315
316 template = '@%9s %7s %7s %14s %12s %9s'
317 header = 'Method', 'Size', 'Ops', 'Time', 'Ops/Sec', 'Ratio'
318 print(template % header)
319 sys.stdout.flush()
320
321 if args.funcs == 'all':
322 benchmarks = [benchmark_add, benchmark_del]
323 elif args.funcs == 'add':
324 benchmarks = [benchmark_add]
325 elif args.funcs == 'del':
326 benchmarks = [benchmark_del]
327 else:
328 raise ValueError(args.funcs)
329
330 for benchmark in benchmarks:
331 benchmark(start, limit, args.times)