##// END OF EJS Templates
revlog: clarify which version use the older API in perf...
marmoute -
r43927:43424f03 default
parent child Browse files
Show More
@@ -1,3837 +1,3838 b''
1 # perf.py - performance test routines
1 # perf.py - performance test routines
2 '''helper extension to measure performance
2 '''helper extension to measure performance
3
3
4 Configurations
4 Configurations
5 ==============
5 ==============
6
6
7 ``perf``
7 ``perf``
8 --------
8 --------
9
9
10 ``all-timing``
10 ``all-timing``
11 When set, additional statistics will be reported for each benchmark: best,
11 When set, additional statistics will be reported for each benchmark: best,
12 worst, median average. If not set only the best timing is reported
12 worst, median average. If not set only the best timing is reported
13 (default: off).
13 (default: off).
14
14
15 ``presleep``
15 ``presleep``
16 number of second to wait before any group of runs (default: 1)
16 number of second to wait before any group of runs (default: 1)
17
17
18 ``pre-run``
18 ``pre-run``
19 number of run to perform before starting measurement.
19 number of run to perform before starting measurement.
20
20
21 ``profile-benchmark``
21 ``profile-benchmark``
22 Enable profiling for the benchmarked section.
22 Enable profiling for the benchmarked section.
23 (The first iteration is benchmarked)
23 (The first iteration is benchmarked)
24
24
25 ``run-limits``
25 ``run-limits``
26 Control the number of runs each benchmark will perform. The option value
26 Control the number of runs each benchmark will perform. The option value
27 should be a list of `<time>-<numberofrun>` pairs. After each run the
27 should be a list of `<time>-<numberofrun>` pairs. After each run the
28 conditions are considered in order with the following logic:
28 conditions are considered in order with the following logic:
29
29
30 If benchmark has been running for <time> seconds, and we have performed
30 If benchmark has been running for <time> seconds, and we have performed
31 <numberofrun> iterations, stop the benchmark,
31 <numberofrun> iterations, stop the benchmark,
32
32
33 The default value is: `3.0-100, 10.0-3`
33 The default value is: `3.0-100, 10.0-3`
34
34
35 ``stub``
35 ``stub``
36 When set, benchmarks will only be run once, useful for testing
36 When set, benchmarks will only be run once, useful for testing
37 (default: off)
37 (default: off)
38 '''
38 '''
39
39
40 # "historical portability" policy of perf.py:
40 # "historical portability" policy of perf.py:
41 #
41 #
42 # We have to do:
42 # We have to do:
43 # - make perf.py "loadable" with as wide Mercurial version as possible
43 # - make perf.py "loadable" with as wide Mercurial version as possible
44 # This doesn't mean that perf commands work correctly with that Mercurial.
44 # This doesn't mean that perf commands work correctly with that Mercurial.
45 # BTW, perf.py itself has been available since 1.1 (or eb240755386d).
45 # BTW, perf.py itself has been available since 1.1 (or eb240755386d).
46 # - make historical perf command work correctly with as wide Mercurial
46 # - make historical perf command work correctly with as wide Mercurial
47 # version as possible
47 # version as possible
48 #
48 #
49 # We have to do, if possible with reasonable cost:
49 # We have to do, if possible with reasonable cost:
50 # - make recent perf command for historical feature work correctly
50 # - make recent perf command for historical feature work correctly
51 # with early Mercurial
51 # with early Mercurial
52 #
52 #
53 # We don't have to do:
53 # We don't have to do:
54 # - make perf command for recent feature work correctly with early
54 # - make perf command for recent feature work correctly with early
55 # Mercurial
55 # Mercurial
56
56
57 from __future__ import absolute_import
57 from __future__ import absolute_import
58 import contextlib
58 import contextlib
59 import functools
59 import functools
60 import gc
60 import gc
61 import os
61 import os
62 import random
62 import random
63 import shutil
63 import shutil
64 import struct
64 import struct
65 import sys
65 import sys
66 import tempfile
66 import tempfile
67 import threading
67 import threading
68 import time
68 import time
69 from mercurial import (
69 from mercurial import (
70 changegroup,
70 changegroup,
71 cmdutil,
71 cmdutil,
72 commands,
72 commands,
73 copies,
73 copies,
74 error,
74 error,
75 extensions,
75 extensions,
76 hg,
76 hg,
77 mdiff,
77 mdiff,
78 merge,
78 merge,
79 revlog,
79 revlog,
80 util,
80 util,
81 )
81 )
82
82
83 # for "historical portability":
83 # for "historical portability":
84 # try to import modules separately (in dict order), and ignore
84 # try to import modules separately (in dict order), and ignore
85 # failure, because these aren't available with early Mercurial
85 # failure, because these aren't available with early Mercurial
86 try:
86 try:
87 from mercurial import branchmap # since 2.5 (or bcee63733aad)
87 from mercurial import branchmap # since 2.5 (or bcee63733aad)
88 except ImportError:
88 except ImportError:
89 pass
89 pass
90 try:
90 try:
91 from mercurial import obsolete # since 2.3 (or ad0d6c2b3279)
91 from mercurial import obsolete # since 2.3 (or ad0d6c2b3279)
92 except ImportError:
92 except ImportError:
93 pass
93 pass
94 try:
94 try:
95 from mercurial import registrar # since 3.7 (or 37d50250b696)
95 from mercurial import registrar # since 3.7 (or 37d50250b696)
96
96
97 dir(registrar) # forcibly load it
97 dir(registrar) # forcibly load it
98 except ImportError:
98 except ImportError:
99 registrar = None
99 registrar = None
100 try:
100 try:
101 from mercurial import repoview # since 2.5 (or 3a6ddacb7198)
101 from mercurial import repoview # since 2.5 (or 3a6ddacb7198)
102 except ImportError:
102 except ImportError:
103 pass
103 pass
104 try:
104 try:
105 from mercurial.utils import repoviewutil # since 5.0
105 from mercurial.utils import repoviewutil # since 5.0
106 except ImportError:
106 except ImportError:
107 repoviewutil = None
107 repoviewutil = None
108 try:
108 try:
109 from mercurial import scmutil # since 1.9 (or 8b252e826c68)
109 from mercurial import scmutil # since 1.9 (or 8b252e826c68)
110 except ImportError:
110 except ImportError:
111 pass
111 pass
112 try:
112 try:
113 from mercurial import setdiscovery # since 1.9 (or cb98fed52495)
113 from mercurial import setdiscovery # since 1.9 (or cb98fed52495)
114 except ImportError:
114 except ImportError:
115 pass
115 pass
116
116
117 try:
117 try:
118 from mercurial import profiling
118 from mercurial import profiling
119 except ImportError:
119 except ImportError:
120 profiling = None
120 profiling = None
121
121
122
122
123 def identity(a):
123 def identity(a):
124 return a
124 return a
125
125
126
126
127 try:
127 try:
128 from mercurial import pycompat
128 from mercurial import pycompat
129
129
130 getargspec = pycompat.getargspec # added to module after 4.5
130 getargspec = pycompat.getargspec # added to module after 4.5
131 _byteskwargs = pycompat.byteskwargs # since 4.1 (or fbc3f73dc802)
131 _byteskwargs = pycompat.byteskwargs # since 4.1 (or fbc3f73dc802)
132 _sysstr = pycompat.sysstr # since 4.0 (or 2219f4f82ede)
132 _sysstr = pycompat.sysstr # since 4.0 (or 2219f4f82ede)
133 _bytestr = pycompat.bytestr # since 4.2 (or b70407bd84d5)
133 _bytestr = pycompat.bytestr # since 4.2 (or b70407bd84d5)
134 _xrange = pycompat.xrange # since 4.8 (or 7eba8f83129b)
134 _xrange = pycompat.xrange # since 4.8 (or 7eba8f83129b)
135 fsencode = pycompat.fsencode # since 3.9 (or f4a5e0e86a7e)
135 fsencode = pycompat.fsencode # since 3.9 (or f4a5e0e86a7e)
136 if pycompat.ispy3:
136 if pycompat.ispy3:
137 _maxint = sys.maxsize # per py3 docs for replacing maxint
137 _maxint = sys.maxsize # per py3 docs for replacing maxint
138 else:
138 else:
139 _maxint = sys.maxint
139 _maxint = sys.maxint
140 except (NameError, ImportError, AttributeError):
140 except (NameError, ImportError, AttributeError):
141 import inspect
141 import inspect
142
142
143 getargspec = inspect.getargspec
143 getargspec = inspect.getargspec
144 _byteskwargs = identity
144 _byteskwargs = identity
145 _bytestr = str
145 _bytestr = str
146 fsencode = identity # no py3 support
146 fsencode = identity # no py3 support
147 _maxint = sys.maxint # no py3 support
147 _maxint = sys.maxint # no py3 support
148 _sysstr = lambda x: x # no py3 support
148 _sysstr = lambda x: x # no py3 support
149 _xrange = xrange
149 _xrange = xrange
150
150
151 try:
151 try:
152 # 4.7+
152 # 4.7+
153 queue = pycompat.queue.Queue
153 queue = pycompat.queue.Queue
154 except (NameError, AttributeError, ImportError):
154 except (NameError, AttributeError, ImportError):
155 # <4.7.
155 # <4.7.
156 try:
156 try:
157 queue = pycompat.queue
157 queue = pycompat.queue
158 except (NameError, AttributeError, ImportError):
158 except (NameError, AttributeError, ImportError):
159 import Queue as queue
159 import Queue as queue
160
160
161 try:
161 try:
162 from mercurial import logcmdutil
162 from mercurial import logcmdutil
163
163
164 makelogtemplater = logcmdutil.maketemplater
164 makelogtemplater = logcmdutil.maketemplater
165 except (AttributeError, ImportError):
165 except (AttributeError, ImportError):
166 try:
166 try:
167 makelogtemplater = cmdutil.makelogtemplater
167 makelogtemplater = cmdutil.makelogtemplater
168 except (AttributeError, ImportError):
168 except (AttributeError, ImportError):
169 makelogtemplater = None
169 makelogtemplater = None
170
170
171 # for "historical portability":
171 # for "historical portability":
172 # define util.safehasattr forcibly, because util.safehasattr has been
172 # define util.safehasattr forcibly, because util.safehasattr has been
173 # available since 1.9.3 (or 94b200a11cf7)
173 # available since 1.9.3 (or 94b200a11cf7)
174 _undefined = object()
174 _undefined = object()
175
175
176
176
177 def safehasattr(thing, attr):
177 def safehasattr(thing, attr):
178 return getattr(thing, _sysstr(attr), _undefined) is not _undefined
178 return getattr(thing, _sysstr(attr), _undefined) is not _undefined
179
179
180
180
181 setattr(util, 'safehasattr', safehasattr)
181 setattr(util, 'safehasattr', safehasattr)
182
182
183 # for "historical portability":
183 # for "historical portability":
184 # define util.timer forcibly, because util.timer has been available
184 # define util.timer forcibly, because util.timer has been available
185 # since ae5d60bb70c9
185 # since ae5d60bb70c9
186 if safehasattr(time, 'perf_counter'):
186 if safehasattr(time, 'perf_counter'):
187 util.timer = time.perf_counter
187 util.timer = time.perf_counter
188 elif os.name == b'nt':
188 elif os.name == b'nt':
189 util.timer = time.clock
189 util.timer = time.clock
190 else:
190 else:
191 util.timer = time.time
191 util.timer = time.time
192
192
193 # for "historical portability":
193 # for "historical portability":
194 # use locally defined empty option list, if formatteropts isn't
194 # use locally defined empty option list, if formatteropts isn't
195 # available, because commands.formatteropts has been available since
195 # available, because commands.formatteropts has been available since
196 # 3.2 (or 7a7eed5176a4), even though formatting itself has been
196 # 3.2 (or 7a7eed5176a4), even though formatting itself has been
197 # available since 2.2 (or ae5f92e154d3)
197 # available since 2.2 (or ae5f92e154d3)
198 formatteropts = getattr(
198 formatteropts = getattr(
199 cmdutil, "formatteropts", getattr(commands, "formatteropts", [])
199 cmdutil, "formatteropts", getattr(commands, "formatteropts", [])
200 )
200 )
201
201
202 # for "historical portability":
202 # for "historical portability":
203 # use locally defined option list, if debugrevlogopts isn't available,
203 # use locally defined option list, if debugrevlogopts isn't available,
204 # because commands.debugrevlogopts has been available since 3.7 (or
204 # because commands.debugrevlogopts has been available since 3.7 (or
205 # 5606f7d0d063), even though cmdutil.openrevlog() has been available
205 # 5606f7d0d063), even though cmdutil.openrevlog() has been available
206 # since 1.9 (or a79fea6b3e77).
206 # since 1.9 (or a79fea6b3e77).
207 revlogopts = getattr(
207 revlogopts = getattr(
208 cmdutil,
208 cmdutil,
209 "debugrevlogopts",
209 "debugrevlogopts",
210 getattr(
210 getattr(
211 commands,
211 commands,
212 "debugrevlogopts",
212 "debugrevlogopts",
213 [
213 [
214 (b'c', b'changelog', False, b'open changelog'),
214 (b'c', b'changelog', False, b'open changelog'),
215 (b'm', b'manifest', False, b'open manifest'),
215 (b'm', b'manifest', False, b'open manifest'),
216 (b'', b'dir', False, b'open directory manifest'),
216 (b'', b'dir', False, b'open directory manifest'),
217 ],
217 ],
218 ),
218 ),
219 )
219 )
220
220
221 cmdtable = {}
221 cmdtable = {}
222
222
223 # for "historical portability":
223 # for "historical portability":
224 # define parsealiases locally, because cmdutil.parsealiases has been
224 # define parsealiases locally, because cmdutil.parsealiases has been
225 # available since 1.5 (or 6252852b4332)
225 # available since 1.5 (or 6252852b4332)
226 def parsealiases(cmd):
226 def parsealiases(cmd):
227 return cmd.split(b"|")
227 return cmd.split(b"|")
228
228
229
229
230 if safehasattr(registrar, 'command'):
230 if safehasattr(registrar, 'command'):
231 command = registrar.command(cmdtable)
231 command = registrar.command(cmdtable)
232 elif safehasattr(cmdutil, 'command'):
232 elif safehasattr(cmdutil, 'command'):
233 command = cmdutil.command(cmdtable)
233 command = cmdutil.command(cmdtable)
234 if b'norepo' not in getargspec(command).args:
234 if b'norepo' not in getargspec(command).args:
235 # for "historical portability":
235 # for "historical portability":
236 # wrap original cmdutil.command, because "norepo" option has
236 # wrap original cmdutil.command, because "norepo" option has
237 # been available since 3.1 (or 75a96326cecb)
237 # been available since 3.1 (or 75a96326cecb)
238 _command = command
238 _command = command
239
239
240 def command(name, options=(), synopsis=None, norepo=False):
240 def command(name, options=(), synopsis=None, norepo=False):
241 if norepo:
241 if norepo:
242 commands.norepo += b' %s' % b' '.join(parsealiases(name))
242 commands.norepo += b' %s' % b' '.join(parsealiases(name))
243 return _command(name, list(options), synopsis)
243 return _command(name, list(options), synopsis)
244
244
245
245
246 else:
246 else:
247 # for "historical portability":
247 # for "historical portability":
248 # define "@command" annotation locally, because cmdutil.command
248 # define "@command" annotation locally, because cmdutil.command
249 # has been available since 1.9 (or 2daa5179e73f)
249 # has been available since 1.9 (or 2daa5179e73f)
250 def command(name, options=(), synopsis=None, norepo=False):
250 def command(name, options=(), synopsis=None, norepo=False):
251 def decorator(func):
251 def decorator(func):
252 if synopsis:
252 if synopsis:
253 cmdtable[name] = func, list(options), synopsis
253 cmdtable[name] = func, list(options), synopsis
254 else:
254 else:
255 cmdtable[name] = func, list(options)
255 cmdtable[name] = func, list(options)
256 if norepo:
256 if norepo:
257 commands.norepo += b' %s' % b' '.join(parsealiases(name))
257 commands.norepo += b' %s' % b' '.join(parsealiases(name))
258 return func
258 return func
259
259
260 return decorator
260 return decorator
261
261
262
262
263 try:
263 try:
264 import mercurial.registrar
264 import mercurial.registrar
265 import mercurial.configitems
265 import mercurial.configitems
266
266
267 configtable = {}
267 configtable = {}
268 configitem = mercurial.registrar.configitem(configtable)
268 configitem = mercurial.registrar.configitem(configtable)
269 configitem(
269 configitem(
270 b'perf',
270 b'perf',
271 b'presleep',
271 b'presleep',
272 default=mercurial.configitems.dynamicdefault,
272 default=mercurial.configitems.dynamicdefault,
273 experimental=True,
273 experimental=True,
274 )
274 )
275 configitem(
275 configitem(
276 b'perf',
276 b'perf',
277 b'stub',
277 b'stub',
278 default=mercurial.configitems.dynamicdefault,
278 default=mercurial.configitems.dynamicdefault,
279 experimental=True,
279 experimental=True,
280 )
280 )
281 configitem(
281 configitem(
282 b'perf',
282 b'perf',
283 b'parentscount',
283 b'parentscount',
284 default=mercurial.configitems.dynamicdefault,
284 default=mercurial.configitems.dynamicdefault,
285 experimental=True,
285 experimental=True,
286 )
286 )
287 configitem(
287 configitem(
288 b'perf',
288 b'perf',
289 b'all-timing',
289 b'all-timing',
290 default=mercurial.configitems.dynamicdefault,
290 default=mercurial.configitems.dynamicdefault,
291 experimental=True,
291 experimental=True,
292 )
292 )
293 configitem(
293 configitem(
294 b'perf', b'pre-run', default=mercurial.configitems.dynamicdefault,
294 b'perf', b'pre-run', default=mercurial.configitems.dynamicdefault,
295 )
295 )
296 configitem(
296 configitem(
297 b'perf',
297 b'perf',
298 b'profile-benchmark',
298 b'profile-benchmark',
299 default=mercurial.configitems.dynamicdefault,
299 default=mercurial.configitems.dynamicdefault,
300 )
300 )
301 configitem(
301 configitem(
302 b'perf',
302 b'perf',
303 b'run-limits',
303 b'run-limits',
304 default=mercurial.configitems.dynamicdefault,
304 default=mercurial.configitems.dynamicdefault,
305 experimental=True,
305 experimental=True,
306 )
306 )
307 except (ImportError, AttributeError):
307 except (ImportError, AttributeError):
308 pass
308 pass
309 except TypeError:
309 except TypeError:
310 # compatibility fix for a11fd395e83f
310 # compatibility fix for a11fd395e83f
311 # hg version: 5.2
311 # hg version: 5.2
312 configitem(
312 configitem(
313 b'perf', b'presleep', default=mercurial.configitems.dynamicdefault,
313 b'perf', b'presleep', default=mercurial.configitems.dynamicdefault,
314 )
314 )
315 configitem(
315 configitem(
316 b'perf', b'stub', default=mercurial.configitems.dynamicdefault,
316 b'perf', b'stub', default=mercurial.configitems.dynamicdefault,
317 )
317 )
318 configitem(
318 configitem(
319 b'perf', b'parentscount', default=mercurial.configitems.dynamicdefault,
319 b'perf', b'parentscount', default=mercurial.configitems.dynamicdefault,
320 )
320 )
321 configitem(
321 configitem(
322 b'perf', b'all-timing', default=mercurial.configitems.dynamicdefault,
322 b'perf', b'all-timing', default=mercurial.configitems.dynamicdefault,
323 )
323 )
324 configitem(
324 configitem(
325 b'perf', b'pre-run', default=mercurial.configitems.dynamicdefault,
325 b'perf', b'pre-run', default=mercurial.configitems.dynamicdefault,
326 )
326 )
327 configitem(
327 configitem(
328 b'perf',
328 b'perf',
329 b'profile-benchmark',
329 b'profile-benchmark',
330 default=mercurial.configitems.dynamicdefault,
330 default=mercurial.configitems.dynamicdefault,
331 )
331 )
332 configitem(
332 configitem(
333 b'perf', b'run-limits', default=mercurial.configitems.dynamicdefault,
333 b'perf', b'run-limits', default=mercurial.configitems.dynamicdefault,
334 )
334 )
335
335
336
336
337 def getlen(ui):
337 def getlen(ui):
338 if ui.configbool(b"perf", b"stub", False):
338 if ui.configbool(b"perf", b"stub", False):
339 return lambda x: 1
339 return lambda x: 1
340 return len
340 return len
341
341
342
342
343 class noop(object):
343 class noop(object):
344 """dummy context manager"""
344 """dummy context manager"""
345
345
346 def __enter__(self):
346 def __enter__(self):
347 pass
347 pass
348
348
349 def __exit__(self, *args):
349 def __exit__(self, *args):
350 pass
350 pass
351
351
352
352
353 NOOPCTX = noop()
353 NOOPCTX = noop()
354
354
355
355
356 def gettimer(ui, opts=None):
356 def gettimer(ui, opts=None):
357 """return a timer function and formatter: (timer, formatter)
357 """return a timer function and formatter: (timer, formatter)
358
358
359 This function exists to gather the creation of formatter in a single
359 This function exists to gather the creation of formatter in a single
360 place instead of duplicating it in all performance commands."""
360 place instead of duplicating it in all performance commands."""
361
361
362 # enforce an idle period before execution to counteract power management
362 # enforce an idle period before execution to counteract power management
363 # experimental config: perf.presleep
363 # experimental config: perf.presleep
364 time.sleep(getint(ui, b"perf", b"presleep", 1))
364 time.sleep(getint(ui, b"perf", b"presleep", 1))
365
365
366 if opts is None:
366 if opts is None:
367 opts = {}
367 opts = {}
368 # redirect all to stderr unless buffer api is in use
368 # redirect all to stderr unless buffer api is in use
369 if not ui._buffers:
369 if not ui._buffers:
370 ui = ui.copy()
370 ui = ui.copy()
371 uifout = safeattrsetter(ui, b'fout', ignoremissing=True)
371 uifout = safeattrsetter(ui, b'fout', ignoremissing=True)
372 if uifout:
372 if uifout:
373 # for "historical portability":
373 # for "historical portability":
374 # ui.fout/ferr have been available since 1.9 (or 4e1ccd4c2b6d)
374 # ui.fout/ferr have been available since 1.9 (or 4e1ccd4c2b6d)
375 uifout.set(ui.ferr)
375 uifout.set(ui.ferr)
376
376
377 # get a formatter
377 # get a formatter
378 uiformatter = getattr(ui, 'formatter', None)
378 uiformatter = getattr(ui, 'formatter', None)
379 if uiformatter:
379 if uiformatter:
380 fm = uiformatter(b'perf', opts)
380 fm = uiformatter(b'perf', opts)
381 else:
381 else:
382 # for "historical portability":
382 # for "historical portability":
383 # define formatter locally, because ui.formatter has been
383 # define formatter locally, because ui.formatter has been
384 # available since 2.2 (or ae5f92e154d3)
384 # available since 2.2 (or ae5f92e154d3)
385 from mercurial import node
385 from mercurial import node
386
386
387 class defaultformatter(object):
387 class defaultformatter(object):
388 """Minimized composition of baseformatter and plainformatter
388 """Minimized composition of baseformatter and plainformatter
389 """
389 """
390
390
391 def __init__(self, ui, topic, opts):
391 def __init__(self, ui, topic, opts):
392 self._ui = ui
392 self._ui = ui
393 if ui.debugflag:
393 if ui.debugflag:
394 self.hexfunc = node.hex
394 self.hexfunc = node.hex
395 else:
395 else:
396 self.hexfunc = node.short
396 self.hexfunc = node.short
397
397
398 def __nonzero__(self):
398 def __nonzero__(self):
399 return False
399 return False
400
400
401 __bool__ = __nonzero__
401 __bool__ = __nonzero__
402
402
403 def startitem(self):
403 def startitem(self):
404 pass
404 pass
405
405
406 def data(self, **data):
406 def data(self, **data):
407 pass
407 pass
408
408
409 def write(self, fields, deftext, *fielddata, **opts):
409 def write(self, fields, deftext, *fielddata, **opts):
410 self._ui.write(deftext % fielddata, **opts)
410 self._ui.write(deftext % fielddata, **opts)
411
411
412 def condwrite(self, cond, fields, deftext, *fielddata, **opts):
412 def condwrite(self, cond, fields, deftext, *fielddata, **opts):
413 if cond:
413 if cond:
414 self._ui.write(deftext % fielddata, **opts)
414 self._ui.write(deftext % fielddata, **opts)
415
415
416 def plain(self, text, **opts):
416 def plain(self, text, **opts):
417 self._ui.write(text, **opts)
417 self._ui.write(text, **opts)
418
418
419 def end(self):
419 def end(self):
420 pass
420 pass
421
421
422 fm = defaultformatter(ui, b'perf', opts)
422 fm = defaultformatter(ui, b'perf', opts)
423
423
424 # stub function, runs code only once instead of in a loop
424 # stub function, runs code only once instead of in a loop
425 # experimental config: perf.stub
425 # experimental config: perf.stub
426 if ui.configbool(b"perf", b"stub", False):
426 if ui.configbool(b"perf", b"stub", False):
427 return functools.partial(stub_timer, fm), fm
427 return functools.partial(stub_timer, fm), fm
428
428
429 # experimental config: perf.all-timing
429 # experimental config: perf.all-timing
430 displayall = ui.configbool(b"perf", b"all-timing", False)
430 displayall = ui.configbool(b"perf", b"all-timing", False)
431
431
432 # experimental config: perf.run-limits
432 # experimental config: perf.run-limits
433 limitspec = ui.configlist(b"perf", b"run-limits", [])
433 limitspec = ui.configlist(b"perf", b"run-limits", [])
434 limits = []
434 limits = []
435 for item in limitspec:
435 for item in limitspec:
436 parts = item.split(b'-', 1)
436 parts = item.split(b'-', 1)
437 if len(parts) < 2:
437 if len(parts) < 2:
438 ui.warn((b'malformatted run limit entry, missing "-": %s\n' % item))
438 ui.warn((b'malformatted run limit entry, missing "-": %s\n' % item))
439 continue
439 continue
440 try:
440 try:
441 time_limit = float(_sysstr(parts[0]))
441 time_limit = float(_sysstr(parts[0]))
442 except ValueError as e:
442 except ValueError as e:
443 ui.warn(
443 ui.warn(
444 (
444 (
445 b'malformatted run limit entry, %s: %s\n'
445 b'malformatted run limit entry, %s: %s\n'
446 % (_bytestr(e), item)
446 % (_bytestr(e), item)
447 )
447 )
448 )
448 )
449 continue
449 continue
450 try:
450 try:
451 run_limit = int(_sysstr(parts[1]))
451 run_limit = int(_sysstr(parts[1]))
452 except ValueError as e:
452 except ValueError as e:
453 ui.warn(
453 ui.warn(
454 (
454 (
455 b'malformatted run limit entry, %s: %s\n'
455 b'malformatted run limit entry, %s: %s\n'
456 % (_bytestr(e), item)
456 % (_bytestr(e), item)
457 )
457 )
458 )
458 )
459 continue
459 continue
460 limits.append((time_limit, run_limit))
460 limits.append((time_limit, run_limit))
461 if not limits:
461 if not limits:
462 limits = DEFAULTLIMITS
462 limits = DEFAULTLIMITS
463
463
464 profiler = None
464 profiler = None
465 if profiling is not None:
465 if profiling is not None:
466 if ui.configbool(b"perf", b"profile-benchmark", False):
466 if ui.configbool(b"perf", b"profile-benchmark", False):
467 profiler = profiling.profile(ui)
467 profiler = profiling.profile(ui)
468
468
469 prerun = getint(ui, b"perf", b"pre-run", 0)
469 prerun = getint(ui, b"perf", b"pre-run", 0)
470 t = functools.partial(
470 t = functools.partial(
471 _timer,
471 _timer,
472 fm,
472 fm,
473 displayall=displayall,
473 displayall=displayall,
474 limits=limits,
474 limits=limits,
475 prerun=prerun,
475 prerun=prerun,
476 profiler=profiler,
476 profiler=profiler,
477 )
477 )
478 return t, fm
478 return t, fm
479
479
480
480
481 def stub_timer(fm, func, setup=None, title=None):
481 def stub_timer(fm, func, setup=None, title=None):
482 if setup is not None:
482 if setup is not None:
483 setup()
483 setup()
484 func()
484 func()
485
485
486
486
487 @contextlib.contextmanager
487 @contextlib.contextmanager
488 def timeone():
488 def timeone():
489 r = []
489 r = []
490 ostart = os.times()
490 ostart = os.times()
491 cstart = util.timer()
491 cstart = util.timer()
492 yield r
492 yield r
493 cstop = util.timer()
493 cstop = util.timer()
494 ostop = os.times()
494 ostop = os.times()
495 a, b = ostart, ostop
495 a, b = ostart, ostop
496 r.append((cstop - cstart, b[0] - a[0], b[1] - a[1]))
496 r.append((cstop - cstart, b[0] - a[0], b[1] - a[1]))
497
497
498
498
499 # list of stop condition (elapsed time, minimal run count)
499 # list of stop condition (elapsed time, minimal run count)
500 DEFAULTLIMITS = (
500 DEFAULTLIMITS = (
501 (3.0, 100),
501 (3.0, 100),
502 (10.0, 3),
502 (10.0, 3),
503 )
503 )
504
504
505
505
506 def _timer(
506 def _timer(
507 fm,
507 fm,
508 func,
508 func,
509 setup=None,
509 setup=None,
510 title=None,
510 title=None,
511 displayall=False,
511 displayall=False,
512 limits=DEFAULTLIMITS,
512 limits=DEFAULTLIMITS,
513 prerun=0,
513 prerun=0,
514 profiler=None,
514 profiler=None,
515 ):
515 ):
516 gc.collect()
516 gc.collect()
517 results = []
517 results = []
518 begin = util.timer()
518 begin = util.timer()
519 count = 0
519 count = 0
520 if profiler is None:
520 if profiler is None:
521 profiler = NOOPCTX
521 profiler = NOOPCTX
522 for i in range(prerun):
522 for i in range(prerun):
523 if setup is not None:
523 if setup is not None:
524 setup()
524 setup()
525 func()
525 func()
526 keepgoing = True
526 keepgoing = True
527 while keepgoing:
527 while keepgoing:
528 if setup is not None:
528 if setup is not None:
529 setup()
529 setup()
530 with profiler:
530 with profiler:
531 with timeone() as item:
531 with timeone() as item:
532 r = func()
532 r = func()
533 profiler = NOOPCTX
533 profiler = NOOPCTX
534 count += 1
534 count += 1
535 results.append(item[0])
535 results.append(item[0])
536 cstop = util.timer()
536 cstop = util.timer()
537 # Look for a stop condition.
537 # Look for a stop condition.
538 elapsed = cstop - begin
538 elapsed = cstop - begin
539 for t, mincount in limits:
539 for t, mincount in limits:
540 if elapsed >= t and count >= mincount:
540 if elapsed >= t and count >= mincount:
541 keepgoing = False
541 keepgoing = False
542 break
542 break
543
543
544 formatone(fm, results, title=title, result=r, displayall=displayall)
544 formatone(fm, results, title=title, result=r, displayall=displayall)
545
545
546
546
547 def formatone(fm, timings, title=None, result=None, displayall=False):
547 def formatone(fm, timings, title=None, result=None, displayall=False):
548
548
549 count = len(timings)
549 count = len(timings)
550
550
551 fm.startitem()
551 fm.startitem()
552
552
553 if title:
553 if title:
554 fm.write(b'title', b'! %s\n', title)
554 fm.write(b'title', b'! %s\n', title)
555 if result:
555 if result:
556 fm.write(b'result', b'! result: %s\n', result)
556 fm.write(b'result', b'! result: %s\n', result)
557
557
558 def display(role, entry):
558 def display(role, entry):
559 prefix = b''
559 prefix = b''
560 if role != b'best':
560 if role != b'best':
561 prefix = b'%s.' % role
561 prefix = b'%s.' % role
562 fm.plain(b'!')
562 fm.plain(b'!')
563 fm.write(prefix + b'wall', b' wall %f', entry[0])
563 fm.write(prefix + b'wall', b' wall %f', entry[0])
564 fm.write(prefix + b'comb', b' comb %f', entry[1] + entry[2])
564 fm.write(prefix + b'comb', b' comb %f', entry[1] + entry[2])
565 fm.write(prefix + b'user', b' user %f', entry[1])
565 fm.write(prefix + b'user', b' user %f', entry[1])
566 fm.write(prefix + b'sys', b' sys %f', entry[2])
566 fm.write(prefix + b'sys', b' sys %f', entry[2])
567 fm.write(prefix + b'count', b' (%s of %%d)' % role, count)
567 fm.write(prefix + b'count', b' (%s of %%d)' % role, count)
568 fm.plain(b'\n')
568 fm.plain(b'\n')
569
569
570 timings.sort()
570 timings.sort()
571 min_val = timings[0]
571 min_val = timings[0]
572 display(b'best', min_val)
572 display(b'best', min_val)
573 if displayall:
573 if displayall:
574 max_val = timings[-1]
574 max_val = timings[-1]
575 display(b'max', max_val)
575 display(b'max', max_val)
576 avg = tuple([sum(x) / count for x in zip(*timings)])
576 avg = tuple([sum(x) / count for x in zip(*timings)])
577 display(b'avg', avg)
577 display(b'avg', avg)
578 median = timings[len(timings) // 2]
578 median = timings[len(timings) // 2]
579 display(b'median', median)
579 display(b'median', median)
580
580
581
581
582 # utilities for historical portability
582 # utilities for historical portability
583
583
584
584
585 def getint(ui, section, name, default):
585 def getint(ui, section, name, default):
586 # for "historical portability":
586 # for "historical portability":
587 # ui.configint has been available since 1.9 (or fa2b596db182)
587 # ui.configint has been available since 1.9 (or fa2b596db182)
588 v = ui.config(section, name, None)
588 v = ui.config(section, name, None)
589 if v is None:
589 if v is None:
590 return default
590 return default
591 try:
591 try:
592 return int(v)
592 return int(v)
593 except ValueError:
593 except ValueError:
594 raise error.ConfigError(
594 raise error.ConfigError(
595 b"%s.%s is not an integer ('%s')" % (section, name, v)
595 b"%s.%s is not an integer ('%s')" % (section, name, v)
596 )
596 )
597
597
598
598
599 def safeattrsetter(obj, name, ignoremissing=False):
599 def safeattrsetter(obj, name, ignoremissing=False):
600 """Ensure that 'obj' has 'name' attribute before subsequent setattr
600 """Ensure that 'obj' has 'name' attribute before subsequent setattr
601
601
602 This function is aborted, if 'obj' doesn't have 'name' attribute
602 This function is aborted, if 'obj' doesn't have 'name' attribute
603 at runtime. This avoids overlooking removal of an attribute, which
603 at runtime. This avoids overlooking removal of an attribute, which
604 breaks assumption of performance measurement, in the future.
604 breaks assumption of performance measurement, in the future.
605
605
606 This function returns the object to (1) assign a new value, and
606 This function returns the object to (1) assign a new value, and
607 (2) restore an original value to the attribute.
607 (2) restore an original value to the attribute.
608
608
609 If 'ignoremissing' is true, missing 'name' attribute doesn't cause
609 If 'ignoremissing' is true, missing 'name' attribute doesn't cause
610 abortion, and this function returns None. This is useful to
610 abortion, and this function returns None. This is useful to
611 examine an attribute, which isn't ensured in all Mercurial
611 examine an attribute, which isn't ensured in all Mercurial
612 versions.
612 versions.
613 """
613 """
614 if not util.safehasattr(obj, name):
614 if not util.safehasattr(obj, name):
615 if ignoremissing:
615 if ignoremissing:
616 return None
616 return None
617 raise error.Abort(
617 raise error.Abort(
618 (
618 (
619 b"missing attribute %s of %s might break assumption"
619 b"missing attribute %s of %s might break assumption"
620 b" of performance measurement"
620 b" of performance measurement"
621 )
621 )
622 % (name, obj)
622 % (name, obj)
623 )
623 )
624
624
625 origvalue = getattr(obj, _sysstr(name))
625 origvalue = getattr(obj, _sysstr(name))
626
626
627 class attrutil(object):
627 class attrutil(object):
628 def set(self, newvalue):
628 def set(self, newvalue):
629 setattr(obj, _sysstr(name), newvalue)
629 setattr(obj, _sysstr(name), newvalue)
630
630
631 def restore(self):
631 def restore(self):
632 setattr(obj, _sysstr(name), origvalue)
632 setattr(obj, _sysstr(name), origvalue)
633
633
634 return attrutil()
634 return attrutil()
635
635
636
636
637 # utilities to examine each internal API changes
637 # utilities to examine each internal API changes
638
638
639
639
640 def getbranchmapsubsettable():
640 def getbranchmapsubsettable():
641 # for "historical portability":
641 # for "historical portability":
642 # subsettable is defined in:
642 # subsettable is defined in:
643 # - branchmap since 2.9 (or 175c6fd8cacc)
643 # - branchmap since 2.9 (or 175c6fd8cacc)
644 # - repoview since 2.5 (or 59a9f18d4587)
644 # - repoview since 2.5 (or 59a9f18d4587)
645 # - repoviewutil since 5.0
645 # - repoviewutil since 5.0
646 for mod in (branchmap, repoview, repoviewutil):
646 for mod in (branchmap, repoview, repoviewutil):
647 subsettable = getattr(mod, 'subsettable', None)
647 subsettable = getattr(mod, 'subsettable', None)
648 if subsettable:
648 if subsettable:
649 return subsettable
649 return subsettable
650
650
651 # bisecting in bcee63733aad::59a9f18d4587 can reach here (both
651 # bisecting in bcee63733aad::59a9f18d4587 can reach here (both
652 # branchmap and repoview modules exist, but subsettable attribute
652 # branchmap and repoview modules exist, but subsettable attribute
653 # doesn't)
653 # doesn't)
654 raise error.Abort(
654 raise error.Abort(
655 b"perfbranchmap not available with this Mercurial",
655 b"perfbranchmap not available with this Mercurial",
656 hint=b"use 2.5 or later",
656 hint=b"use 2.5 or later",
657 )
657 )
658
658
659
659
660 def getsvfs(repo):
660 def getsvfs(repo):
661 """Return appropriate object to access files under .hg/store
661 """Return appropriate object to access files under .hg/store
662 """
662 """
663 # for "historical portability":
663 # for "historical portability":
664 # repo.svfs has been available since 2.3 (or 7034365089bf)
664 # repo.svfs has been available since 2.3 (or 7034365089bf)
665 svfs = getattr(repo, 'svfs', None)
665 svfs = getattr(repo, 'svfs', None)
666 if svfs:
666 if svfs:
667 return svfs
667 return svfs
668 else:
668 else:
669 return getattr(repo, 'sopener')
669 return getattr(repo, 'sopener')
670
670
671
671
672 def getvfs(repo):
672 def getvfs(repo):
673 """Return appropriate object to access files under .hg
673 """Return appropriate object to access files under .hg
674 """
674 """
675 # for "historical portability":
675 # for "historical portability":
676 # repo.vfs has been available since 2.3 (or 7034365089bf)
676 # repo.vfs has been available since 2.3 (or 7034365089bf)
677 vfs = getattr(repo, 'vfs', None)
677 vfs = getattr(repo, 'vfs', None)
678 if vfs:
678 if vfs:
679 return vfs
679 return vfs
680 else:
680 else:
681 return getattr(repo, 'opener')
681 return getattr(repo, 'opener')
682
682
683
683
684 def repocleartagscachefunc(repo):
684 def repocleartagscachefunc(repo):
685 """Return the function to clear tags cache according to repo internal API
685 """Return the function to clear tags cache according to repo internal API
686 """
686 """
687 if util.safehasattr(repo, b'_tagscache'): # since 2.0 (or 9dca7653b525)
687 if util.safehasattr(repo, b'_tagscache'): # since 2.0 (or 9dca7653b525)
688 # in this case, setattr(repo, '_tagscache', None) or so isn't
688 # in this case, setattr(repo, '_tagscache', None) or so isn't
689 # correct way to clear tags cache, because existing code paths
689 # correct way to clear tags cache, because existing code paths
690 # expect _tagscache to be a structured object.
690 # expect _tagscache to be a structured object.
691 def clearcache():
691 def clearcache():
692 # _tagscache has been filteredpropertycache since 2.5 (or
692 # _tagscache has been filteredpropertycache since 2.5 (or
693 # 98c867ac1330), and delattr() can't work in such case
693 # 98c867ac1330), and delattr() can't work in such case
694 if '_tagscache' in vars(repo):
694 if '_tagscache' in vars(repo):
695 del repo.__dict__['_tagscache']
695 del repo.__dict__['_tagscache']
696
696
697 return clearcache
697 return clearcache
698
698
699 repotags = safeattrsetter(repo, b'_tags', ignoremissing=True)
699 repotags = safeattrsetter(repo, b'_tags', ignoremissing=True)
700 if repotags: # since 1.4 (or 5614a628d173)
700 if repotags: # since 1.4 (or 5614a628d173)
701 return lambda: repotags.set(None)
701 return lambda: repotags.set(None)
702
702
703 repotagscache = safeattrsetter(repo, b'tagscache', ignoremissing=True)
703 repotagscache = safeattrsetter(repo, b'tagscache', ignoremissing=True)
704 if repotagscache: # since 0.6 (or d7df759d0e97)
704 if repotagscache: # since 0.6 (or d7df759d0e97)
705 return lambda: repotagscache.set(None)
705 return lambda: repotagscache.set(None)
706
706
707 # Mercurial earlier than 0.6 (or d7df759d0e97) logically reaches
707 # Mercurial earlier than 0.6 (or d7df759d0e97) logically reaches
708 # this point, but it isn't so problematic, because:
708 # this point, but it isn't so problematic, because:
709 # - repo.tags of such Mercurial isn't "callable", and repo.tags()
709 # - repo.tags of such Mercurial isn't "callable", and repo.tags()
710 # in perftags() causes failure soon
710 # in perftags() causes failure soon
711 # - perf.py itself has been available since 1.1 (or eb240755386d)
711 # - perf.py itself has been available since 1.1 (or eb240755386d)
712 raise error.Abort(b"tags API of this hg command is unknown")
712 raise error.Abort(b"tags API of this hg command is unknown")
713
713
714
714
715 # utilities to clear cache
715 # utilities to clear cache
716
716
717
717
718 def clearfilecache(obj, attrname):
718 def clearfilecache(obj, attrname):
719 unfiltered = getattr(obj, 'unfiltered', None)
719 unfiltered = getattr(obj, 'unfiltered', None)
720 if unfiltered is not None:
720 if unfiltered is not None:
721 obj = obj.unfiltered()
721 obj = obj.unfiltered()
722 if attrname in vars(obj):
722 if attrname in vars(obj):
723 delattr(obj, attrname)
723 delattr(obj, attrname)
724 obj._filecache.pop(attrname, None)
724 obj._filecache.pop(attrname, None)
725
725
726
726
727 def clearchangelog(repo):
727 def clearchangelog(repo):
728 if repo is not repo.unfiltered():
728 if repo is not repo.unfiltered():
729 object.__setattr__(repo, '_clcachekey', None)
729 object.__setattr__(repo, '_clcachekey', None)
730 object.__setattr__(repo, '_clcache', None)
730 object.__setattr__(repo, '_clcache', None)
731 clearfilecache(repo.unfiltered(), 'changelog')
731 clearfilecache(repo.unfiltered(), 'changelog')
732
732
733
733
734 # perf commands
734 # perf commands
735
735
736
736
737 @command(b'perfwalk', formatteropts)
737 @command(b'perfwalk', formatteropts)
738 def perfwalk(ui, repo, *pats, **opts):
738 def perfwalk(ui, repo, *pats, **opts):
739 opts = _byteskwargs(opts)
739 opts = _byteskwargs(opts)
740 timer, fm = gettimer(ui, opts)
740 timer, fm = gettimer(ui, opts)
741 m = scmutil.match(repo[None], pats, {})
741 m = scmutil.match(repo[None], pats, {})
742 timer(
742 timer(
743 lambda: len(
743 lambda: len(
744 list(
744 list(
745 repo.dirstate.walk(m, subrepos=[], unknown=True, ignored=False)
745 repo.dirstate.walk(m, subrepos=[], unknown=True, ignored=False)
746 )
746 )
747 )
747 )
748 )
748 )
749 fm.end()
749 fm.end()
750
750
751
751
752 @command(b'perfannotate', formatteropts)
752 @command(b'perfannotate', formatteropts)
753 def perfannotate(ui, repo, f, **opts):
753 def perfannotate(ui, repo, f, **opts):
754 opts = _byteskwargs(opts)
754 opts = _byteskwargs(opts)
755 timer, fm = gettimer(ui, opts)
755 timer, fm = gettimer(ui, opts)
756 fc = repo[b'.'][f]
756 fc = repo[b'.'][f]
757 timer(lambda: len(fc.annotate(True)))
757 timer(lambda: len(fc.annotate(True)))
758 fm.end()
758 fm.end()
759
759
760
760
761 @command(
761 @command(
762 b'perfstatus',
762 b'perfstatus',
763 [
763 [
764 (b'u', b'unknown', False, b'ask status to look for unknown files'),
764 (b'u', b'unknown', False, b'ask status to look for unknown files'),
765 (b'', b'dirstate', False, b'benchmark the internal dirstate call'),
765 (b'', b'dirstate', False, b'benchmark the internal dirstate call'),
766 ]
766 ]
767 + formatteropts,
767 + formatteropts,
768 )
768 )
769 def perfstatus(ui, repo, **opts):
769 def perfstatus(ui, repo, **opts):
770 """benchmark the performance of a single status call
770 """benchmark the performance of a single status call
771
771
772 The repository data are preserved between each call.
772 The repository data are preserved between each call.
773
773
774 By default, only the status of the tracked file are requested. If
774 By default, only the status of the tracked file are requested. If
775 `--unknown` is passed, the "unknown" files are also tracked.
775 `--unknown` is passed, the "unknown" files are also tracked.
776 """
776 """
777 opts = _byteskwargs(opts)
777 opts = _byteskwargs(opts)
778 # m = match.always(repo.root, repo.getcwd())
778 # m = match.always(repo.root, repo.getcwd())
779 # timer(lambda: sum(map(len, repo.dirstate.status(m, [], False, False,
779 # timer(lambda: sum(map(len, repo.dirstate.status(m, [], False, False,
780 # False))))
780 # False))))
781 timer, fm = gettimer(ui, opts)
781 timer, fm = gettimer(ui, opts)
782 if opts[b'dirstate']:
782 if opts[b'dirstate']:
783 dirstate = repo.dirstate
783 dirstate = repo.dirstate
784 m = scmutil.matchall(repo)
784 m = scmutil.matchall(repo)
785 unknown = opts[b'unknown']
785 unknown = opts[b'unknown']
786
786
787 def status_dirstate():
787 def status_dirstate():
788 s = dirstate.status(
788 s = dirstate.status(
789 m, subrepos=[], ignored=False, clean=False, unknown=unknown
789 m, subrepos=[], ignored=False, clean=False, unknown=unknown
790 )
790 )
791 sum(map(len, s))
791 sum(map(len, s))
792
792
793 timer(status_dirstate)
793 timer(status_dirstate)
794 else:
794 else:
795 timer(lambda: sum(map(len, repo.status(unknown=opts[b'unknown']))))
795 timer(lambda: sum(map(len, repo.status(unknown=opts[b'unknown']))))
796 fm.end()
796 fm.end()
797
797
798
798
799 @command(b'perfaddremove', formatteropts)
799 @command(b'perfaddremove', formatteropts)
800 def perfaddremove(ui, repo, **opts):
800 def perfaddremove(ui, repo, **opts):
801 opts = _byteskwargs(opts)
801 opts = _byteskwargs(opts)
802 timer, fm = gettimer(ui, opts)
802 timer, fm = gettimer(ui, opts)
803 try:
803 try:
804 oldquiet = repo.ui.quiet
804 oldquiet = repo.ui.quiet
805 repo.ui.quiet = True
805 repo.ui.quiet = True
806 matcher = scmutil.match(repo[None])
806 matcher = scmutil.match(repo[None])
807 opts[b'dry_run'] = True
807 opts[b'dry_run'] = True
808 if b'uipathfn' in getargspec(scmutil.addremove).args:
808 if b'uipathfn' in getargspec(scmutil.addremove).args:
809 uipathfn = scmutil.getuipathfn(repo)
809 uipathfn = scmutil.getuipathfn(repo)
810 timer(lambda: scmutil.addremove(repo, matcher, b"", uipathfn, opts))
810 timer(lambda: scmutil.addremove(repo, matcher, b"", uipathfn, opts))
811 else:
811 else:
812 timer(lambda: scmutil.addremove(repo, matcher, b"", opts))
812 timer(lambda: scmutil.addremove(repo, matcher, b"", opts))
813 finally:
813 finally:
814 repo.ui.quiet = oldquiet
814 repo.ui.quiet = oldquiet
815 fm.end()
815 fm.end()
816
816
817
817
818 def clearcaches(cl):
818 def clearcaches(cl):
819 # behave somewhat consistently across internal API changes
819 # behave somewhat consistently across internal API changes
820 if util.safehasattr(cl, b'clearcaches'):
820 if util.safehasattr(cl, b'clearcaches'):
821 cl.clearcaches()
821 cl.clearcaches()
822 elif util.safehasattr(cl, b'_nodecache'):
822 elif util.safehasattr(cl, b'_nodecache'):
823 # <= hg-5.2
823 from mercurial.node import nullid, nullrev
824 from mercurial.node import nullid, nullrev
824
825
825 cl._nodecache = {nullid: nullrev}
826 cl._nodecache = {nullid: nullrev}
826 cl._nodepos = None
827 cl._nodepos = None
827
828
828
829
829 @command(b'perfheads', formatteropts)
830 @command(b'perfheads', formatteropts)
830 def perfheads(ui, repo, **opts):
831 def perfheads(ui, repo, **opts):
831 """benchmark the computation of a changelog heads"""
832 """benchmark the computation of a changelog heads"""
832 opts = _byteskwargs(opts)
833 opts = _byteskwargs(opts)
833 timer, fm = gettimer(ui, opts)
834 timer, fm = gettimer(ui, opts)
834 cl = repo.changelog
835 cl = repo.changelog
835
836
836 def s():
837 def s():
837 clearcaches(cl)
838 clearcaches(cl)
838
839
839 def d():
840 def d():
840 len(cl.headrevs())
841 len(cl.headrevs())
841
842
842 timer(d, setup=s)
843 timer(d, setup=s)
843 fm.end()
844 fm.end()
844
845
845
846
846 @command(
847 @command(
847 b'perftags',
848 b'perftags',
848 formatteropts
849 formatteropts
849 + [(b'', b'clear-revlogs', False, b'refresh changelog and manifest'),],
850 + [(b'', b'clear-revlogs', False, b'refresh changelog and manifest'),],
850 )
851 )
851 def perftags(ui, repo, **opts):
852 def perftags(ui, repo, **opts):
852 opts = _byteskwargs(opts)
853 opts = _byteskwargs(opts)
853 timer, fm = gettimer(ui, opts)
854 timer, fm = gettimer(ui, opts)
854 repocleartagscache = repocleartagscachefunc(repo)
855 repocleartagscache = repocleartagscachefunc(repo)
855 clearrevlogs = opts[b'clear_revlogs']
856 clearrevlogs = opts[b'clear_revlogs']
856
857
857 def s():
858 def s():
858 if clearrevlogs:
859 if clearrevlogs:
859 clearchangelog(repo)
860 clearchangelog(repo)
860 clearfilecache(repo.unfiltered(), 'manifest')
861 clearfilecache(repo.unfiltered(), 'manifest')
861 repocleartagscache()
862 repocleartagscache()
862
863
863 def t():
864 def t():
864 return len(repo.tags())
865 return len(repo.tags())
865
866
866 timer(t, setup=s)
867 timer(t, setup=s)
867 fm.end()
868 fm.end()
868
869
869
870
870 @command(b'perfancestors', formatteropts)
871 @command(b'perfancestors', formatteropts)
871 def perfancestors(ui, repo, **opts):
872 def perfancestors(ui, repo, **opts):
872 opts = _byteskwargs(opts)
873 opts = _byteskwargs(opts)
873 timer, fm = gettimer(ui, opts)
874 timer, fm = gettimer(ui, opts)
874 heads = repo.changelog.headrevs()
875 heads = repo.changelog.headrevs()
875
876
876 def d():
877 def d():
877 for a in repo.changelog.ancestors(heads):
878 for a in repo.changelog.ancestors(heads):
878 pass
879 pass
879
880
880 timer(d)
881 timer(d)
881 fm.end()
882 fm.end()
882
883
883
884
884 @command(b'perfancestorset', formatteropts)
885 @command(b'perfancestorset', formatteropts)
885 def perfancestorset(ui, repo, revset, **opts):
886 def perfancestorset(ui, repo, revset, **opts):
886 opts = _byteskwargs(opts)
887 opts = _byteskwargs(opts)
887 timer, fm = gettimer(ui, opts)
888 timer, fm = gettimer(ui, opts)
888 revs = repo.revs(revset)
889 revs = repo.revs(revset)
889 heads = repo.changelog.headrevs()
890 heads = repo.changelog.headrevs()
890
891
891 def d():
892 def d():
892 s = repo.changelog.ancestors(heads)
893 s = repo.changelog.ancestors(heads)
893 for rev in revs:
894 for rev in revs:
894 rev in s
895 rev in s
895
896
896 timer(d)
897 timer(d)
897 fm.end()
898 fm.end()
898
899
899
900
900 @command(b'perfdiscovery', formatteropts, b'PATH')
901 @command(b'perfdiscovery', formatteropts, b'PATH')
901 def perfdiscovery(ui, repo, path, **opts):
902 def perfdiscovery(ui, repo, path, **opts):
902 """benchmark discovery between local repo and the peer at given path
903 """benchmark discovery between local repo and the peer at given path
903 """
904 """
904 repos = [repo, None]
905 repos = [repo, None]
905 timer, fm = gettimer(ui, opts)
906 timer, fm = gettimer(ui, opts)
906 path = ui.expandpath(path)
907 path = ui.expandpath(path)
907
908
908 def s():
909 def s():
909 repos[1] = hg.peer(ui, opts, path)
910 repos[1] = hg.peer(ui, opts, path)
910
911
911 def d():
912 def d():
912 setdiscovery.findcommonheads(ui, *repos)
913 setdiscovery.findcommonheads(ui, *repos)
913
914
914 timer(d, setup=s)
915 timer(d, setup=s)
915 fm.end()
916 fm.end()
916
917
917
918
918 @command(
919 @command(
919 b'perfbookmarks',
920 b'perfbookmarks',
920 formatteropts
921 formatteropts
921 + [(b'', b'clear-revlogs', False, b'refresh changelog and manifest'),],
922 + [(b'', b'clear-revlogs', False, b'refresh changelog and manifest'),],
922 )
923 )
923 def perfbookmarks(ui, repo, **opts):
924 def perfbookmarks(ui, repo, **opts):
924 """benchmark parsing bookmarks from disk to memory"""
925 """benchmark parsing bookmarks from disk to memory"""
925 opts = _byteskwargs(opts)
926 opts = _byteskwargs(opts)
926 timer, fm = gettimer(ui, opts)
927 timer, fm = gettimer(ui, opts)
927
928
928 clearrevlogs = opts[b'clear_revlogs']
929 clearrevlogs = opts[b'clear_revlogs']
929
930
930 def s():
931 def s():
931 if clearrevlogs:
932 if clearrevlogs:
932 clearchangelog(repo)
933 clearchangelog(repo)
933 clearfilecache(repo, b'_bookmarks')
934 clearfilecache(repo, b'_bookmarks')
934
935
935 def d():
936 def d():
936 repo._bookmarks
937 repo._bookmarks
937
938
938 timer(d, setup=s)
939 timer(d, setup=s)
939 fm.end()
940 fm.end()
940
941
941
942
942 @command(b'perfbundleread', formatteropts, b'BUNDLE')
943 @command(b'perfbundleread', formatteropts, b'BUNDLE')
943 def perfbundleread(ui, repo, bundlepath, **opts):
944 def perfbundleread(ui, repo, bundlepath, **opts):
944 """Benchmark reading of bundle files.
945 """Benchmark reading of bundle files.
945
946
946 This command is meant to isolate the I/O part of bundle reading as
947 This command is meant to isolate the I/O part of bundle reading as
947 much as possible.
948 much as possible.
948 """
949 """
949 from mercurial import (
950 from mercurial import (
950 bundle2,
951 bundle2,
951 exchange,
952 exchange,
952 streamclone,
953 streamclone,
953 )
954 )
954
955
955 opts = _byteskwargs(opts)
956 opts = _byteskwargs(opts)
956
957
957 def makebench(fn):
958 def makebench(fn):
958 def run():
959 def run():
959 with open(bundlepath, b'rb') as fh:
960 with open(bundlepath, b'rb') as fh:
960 bundle = exchange.readbundle(ui, fh, bundlepath)
961 bundle = exchange.readbundle(ui, fh, bundlepath)
961 fn(bundle)
962 fn(bundle)
962
963
963 return run
964 return run
964
965
965 def makereadnbytes(size):
966 def makereadnbytes(size):
966 def run():
967 def run():
967 with open(bundlepath, b'rb') as fh:
968 with open(bundlepath, b'rb') as fh:
968 bundle = exchange.readbundle(ui, fh, bundlepath)
969 bundle = exchange.readbundle(ui, fh, bundlepath)
969 while bundle.read(size):
970 while bundle.read(size):
970 pass
971 pass
971
972
972 return run
973 return run
973
974
974 def makestdioread(size):
975 def makestdioread(size):
975 def run():
976 def run():
976 with open(bundlepath, b'rb') as fh:
977 with open(bundlepath, b'rb') as fh:
977 while fh.read(size):
978 while fh.read(size):
978 pass
979 pass
979
980
980 return run
981 return run
981
982
982 # bundle1
983 # bundle1
983
984
984 def deltaiter(bundle):
985 def deltaiter(bundle):
985 for delta in bundle.deltaiter():
986 for delta in bundle.deltaiter():
986 pass
987 pass
987
988
988 def iterchunks(bundle):
989 def iterchunks(bundle):
989 for chunk in bundle.getchunks():
990 for chunk in bundle.getchunks():
990 pass
991 pass
991
992
992 # bundle2
993 # bundle2
993
994
994 def forwardchunks(bundle):
995 def forwardchunks(bundle):
995 for chunk in bundle._forwardchunks():
996 for chunk in bundle._forwardchunks():
996 pass
997 pass
997
998
998 def iterparts(bundle):
999 def iterparts(bundle):
999 for part in bundle.iterparts():
1000 for part in bundle.iterparts():
1000 pass
1001 pass
1001
1002
1002 def iterpartsseekable(bundle):
1003 def iterpartsseekable(bundle):
1003 for part in bundle.iterparts(seekable=True):
1004 for part in bundle.iterparts(seekable=True):
1004 pass
1005 pass
1005
1006
1006 def seek(bundle):
1007 def seek(bundle):
1007 for part in bundle.iterparts(seekable=True):
1008 for part in bundle.iterparts(seekable=True):
1008 part.seek(0, os.SEEK_END)
1009 part.seek(0, os.SEEK_END)
1009
1010
1010 def makepartreadnbytes(size):
1011 def makepartreadnbytes(size):
1011 def run():
1012 def run():
1012 with open(bundlepath, b'rb') as fh:
1013 with open(bundlepath, b'rb') as fh:
1013 bundle = exchange.readbundle(ui, fh, bundlepath)
1014 bundle = exchange.readbundle(ui, fh, bundlepath)
1014 for part in bundle.iterparts():
1015 for part in bundle.iterparts():
1015 while part.read(size):
1016 while part.read(size):
1016 pass
1017 pass
1017
1018
1018 return run
1019 return run
1019
1020
1020 benches = [
1021 benches = [
1021 (makestdioread(8192), b'read(8k)'),
1022 (makestdioread(8192), b'read(8k)'),
1022 (makestdioread(16384), b'read(16k)'),
1023 (makestdioread(16384), b'read(16k)'),
1023 (makestdioread(32768), b'read(32k)'),
1024 (makestdioread(32768), b'read(32k)'),
1024 (makestdioread(131072), b'read(128k)'),
1025 (makestdioread(131072), b'read(128k)'),
1025 ]
1026 ]
1026
1027
1027 with open(bundlepath, b'rb') as fh:
1028 with open(bundlepath, b'rb') as fh:
1028 bundle = exchange.readbundle(ui, fh, bundlepath)
1029 bundle = exchange.readbundle(ui, fh, bundlepath)
1029
1030
1030 if isinstance(bundle, changegroup.cg1unpacker):
1031 if isinstance(bundle, changegroup.cg1unpacker):
1031 benches.extend(
1032 benches.extend(
1032 [
1033 [
1033 (makebench(deltaiter), b'cg1 deltaiter()'),
1034 (makebench(deltaiter), b'cg1 deltaiter()'),
1034 (makebench(iterchunks), b'cg1 getchunks()'),
1035 (makebench(iterchunks), b'cg1 getchunks()'),
1035 (makereadnbytes(8192), b'cg1 read(8k)'),
1036 (makereadnbytes(8192), b'cg1 read(8k)'),
1036 (makereadnbytes(16384), b'cg1 read(16k)'),
1037 (makereadnbytes(16384), b'cg1 read(16k)'),
1037 (makereadnbytes(32768), b'cg1 read(32k)'),
1038 (makereadnbytes(32768), b'cg1 read(32k)'),
1038 (makereadnbytes(131072), b'cg1 read(128k)'),
1039 (makereadnbytes(131072), b'cg1 read(128k)'),
1039 ]
1040 ]
1040 )
1041 )
1041 elif isinstance(bundle, bundle2.unbundle20):
1042 elif isinstance(bundle, bundle2.unbundle20):
1042 benches.extend(
1043 benches.extend(
1043 [
1044 [
1044 (makebench(forwardchunks), b'bundle2 forwardchunks()'),
1045 (makebench(forwardchunks), b'bundle2 forwardchunks()'),
1045 (makebench(iterparts), b'bundle2 iterparts()'),
1046 (makebench(iterparts), b'bundle2 iterparts()'),
1046 (
1047 (
1047 makebench(iterpartsseekable),
1048 makebench(iterpartsseekable),
1048 b'bundle2 iterparts() seekable',
1049 b'bundle2 iterparts() seekable',
1049 ),
1050 ),
1050 (makebench(seek), b'bundle2 part seek()'),
1051 (makebench(seek), b'bundle2 part seek()'),
1051 (makepartreadnbytes(8192), b'bundle2 part read(8k)'),
1052 (makepartreadnbytes(8192), b'bundle2 part read(8k)'),
1052 (makepartreadnbytes(16384), b'bundle2 part read(16k)'),
1053 (makepartreadnbytes(16384), b'bundle2 part read(16k)'),
1053 (makepartreadnbytes(32768), b'bundle2 part read(32k)'),
1054 (makepartreadnbytes(32768), b'bundle2 part read(32k)'),
1054 (makepartreadnbytes(131072), b'bundle2 part read(128k)'),
1055 (makepartreadnbytes(131072), b'bundle2 part read(128k)'),
1055 ]
1056 ]
1056 )
1057 )
1057 elif isinstance(bundle, streamclone.streamcloneapplier):
1058 elif isinstance(bundle, streamclone.streamcloneapplier):
1058 raise error.Abort(b'stream clone bundles not supported')
1059 raise error.Abort(b'stream clone bundles not supported')
1059 else:
1060 else:
1060 raise error.Abort(b'unhandled bundle type: %s' % type(bundle))
1061 raise error.Abort(b'unhandled bundle type: %s' % type(bundle))
1061
1062
1062 for fn, title in benches:
1063 for fn, title in benches:
1063 timer, fm = gettimer(ui, opts)
1064 timer, fm = gettimer(ui, opts)
1064 timer(fn, title=title)
1065 timer(fn, title=title)
1065 fm.end()
1066 fm.end()
1066
1067
1067
1068
1068 @command(
1069 @command(
1069 b'perfchangegroupchangelog',
1070 b'perfchangegroupchangelog',
1070 formatteropts
1071 formatteropts
1071 + [
1072 + [
1072 (b'', b'cgversion', b'02', b'changegroup version'),
1073 (b'', b'cgversion', b'02', b'changegroup version'),
1073 (b'r', b'rev', b'', b'revisions to add to changegroup'),
1074 (b'r', b'rev', b'', b'revisions to add to changegroup'),
1074 ],
1075 ],
1075 )
1076 )
1076 def perfchangegroupchangelog(ui, repo, cgversion=b'02', rev=None, **opts):
1077 def perfchangegroupchangelog(ui, repo, cgversion=b'02', rev=None, **opts):
1077 """Benchmark producing a changelog group for a changegroup.
1078 """Benchmark producing a changelog group for a changegroup.
1078
1079
1079 This measures the time spent processing the changelog during a
1080 This measures the time spent processing the changelog during a
1080 bundle operation. This occurs during `hg bundle` and on a server
1081 bundle operation. This occurs during `hg bundle` and on a server
1081 processing a `getbundle` wire protocol request (handles clones
1082 processing a `getbundle` wire protocol request (handles clones
1082 and pull requests).
1083 and pull requests).
1083
1084
1084 By default, all revisions are added to the changegroup.
1085 By default, all revisions are added to the changegroup.
1085 """
1086 """
1086 opts = _byteskwargs(opts)
1087 opts = _byteskwargs(opts)
1087 cl = repo.changelog
1088 cl = repo.changelog
1088 nodes = [cl.lookup(r) for r in repo.revs(rev or b'all()')]
1089 nodes = [cl.lookup(r) for r in repo.revs(rev or b'all()')]
1089 bundler = changegroup.getbundler(cgversion, repo)
1090 bundler = changegroup.getbundler(cgversion, repo)
1090
1091
1091 def d():
1092 def d():
1092 state, chunks = bundler._generatechangelog(cl, nodes)
1093 state, chunks = bundler._generatechangelog(cl, nodes)
1093 for chunk in chunks:
1094 for chunk in chunks:
1094 pass
1095 pass
1095
1096
1096 timer, fm = gettimer(ui, opts)
1097 timer, fm = gettimer(ui, opts)
1097
1098
1098 # Terminal printing can interfere with timing. So disable it.
1099 # Terminal printing can interfere with timing. So disable it.
1099 with ui.configoverride({(b'progress', b'disable'): True}):
1100 with ui.configoverride({(b'progress', b'disable'): True}):
1100 timer(d)
1101 timer(d)
1101
1102
1102 fm.end()
1103 fm.end()
1103
1104
1104
1105
1105 @command(b'perfdirs', formatteropts)
1106 @command(b'perfdirs', formatteropts)
1106 def perfdirs(ui, repo, **opts):
1107 def perfdirs(ui, repo, **opts):
1107 opts = _byteskwargs(opts)
1108 opts = _byteskwargs(opts)
1108 timer, fm = gettimer(ui, opts)
1109 timer, fm = gettimer(ui, opts)
1109 dirstate = repo.dirstate
1110 dirstate = repo.dirstate
1110 b'a' in dirstate
1111 b'a' in dirstate
1111
1112
1112 def d():
1113 def d():
1113 dirstate.hasdir(b'a')
1114 dirstate.hasdir(b'a')
1114 del dirstate._map._dirs
1115 del dirstate._map._dirs
1115
1116
1116 timer(d)
1117 timer(d)
1117 fm.end()
1118 fm.end()
1118
1119
1119
1120
1120 @command(
1121 @command(
1121 b'perfdirstate',
1122 b'perfdirstate',
1122 [
1123 [
1123 (
1124 (
1124 b'',
1125 b'',
1125 b'iteration',
1126 b'iteration',
1126 None,
1127 None,
1127 b'benchmark a full iteration for the dirstate',
1128 b'benchmark a full iteration for the dirstate',
1128 ),
1129 ),
1129 (
1130 (
1130 b'',
1131 b'',
1131 b'contains',
1132 b'contains',
1132 None,
1133 None,
1133 b'benchmark a large amount of `nf in dirstate` calls',
1134 b'benchmark a large amount of `nf in dirstate` calls',
1134 ),
1135 ),
1135 ]
1136 ]
1136 + formatteropts,
1137 + formatteropts,
1137 )
1138 )
1138 def perfdirstate(ui, repo, **opts):
1139 def perfdirstate(ui, repo, **opts):
1139 """benchmap the time of various distate operations
1140 """benchmap the time of various distate operations
1140
1141
1141 By default benchmark the time necessary to load a dirstate from scratch.
1142 By default benchmark the time necessary to load a dirstate from scratch.
1142 The dirstate is loaded to the point were a "contains" request can be
1143 The dirstate is loaded to the point were a "contains" request can be
1143 answered.
1144 answered.
1144 """
1145 """
1145 opts = _byteskwargs(opts)
1146 opts = _byteskwargs(opts)
1146 timer, fm = gettimer(ui, opts)
1147 timer, fm = gettimer(ui, opts)
1147 b"a" in repo.dirstate
1148 b"a" in repo.dirstate
1148
1149
1149 if opts[b'iteration'] and opts[b'contains']:
1150 if opts[b'iteration'] and opts[b'contains']:
1150 msg = b'only specify one of --iteration or --contains'
1151 msg = b'only specify one of --iteration or --contains'
1151 raise error.Abort(msg)
1152 raise error.Abort(msg)
1152
1153
1153 if opts[b'iteration']:
1154 if opts[b'iteration']:
1154 setup = None
1155 setup = None
1155 dirstate = repo.dirstate
1156 dirstate = repo.dirstate
1156
1157
1157 def d():
1158 def d():
1158 for f in dirstate:
1159 for f in dirstate:
1159 pass
1160 pass
1160
1161
1161 elif opts[b'contains']:
1162 elif opts[b'contains']:
1162 setup = None
1163 setup = None
1163 dirstate = repo.dirstate
1164 dirstate = repo.dirstate
1164 allfiles = list(dirstate)
1165 allfiles = list(dirstate)
1165 # also add file path that will be "missing" from the dirstate
1166 # also add file path that will be "missing" from the dirstate
1166 allfiles.extend([f[::-1] for f in allfiles])
1167 allfiles.extend([f[::-1] for f in allfiles])
1167
1168
1168 def d():
1169 def d():
1169 for f in allfiles:
1170 for f in allfiles:
1170 f in dirstate
1171 f in dirstate
1171
1172
1172 else:
1173 else:
1173
1174
1174 def setup():
1175 def setup():
1175 repo.dirstate.invalidate()
1176 repo.dirstate.invalidate()
1176
1177
1177 def d():
1178 def d():
1178 b"a" in repo.dirstate
1179 b"a" in repo.dirstate
1179
1180
1180 timer(d, setup=setup)
1181 timer(d, setup=setup)
1181 fm.end()
1182 fm.end()
1182
1183
1183
1184
1184 @command(b'perfdirstatedirs', formatteropts)
1185 @command(b'perfdirstatedirs', formatteropts)
1185 def perfdirstatedirs(ui, repo, **opts):
1186 def perfdirstatedirs(ui, repo, **opts):
1186 """benchmap a 'dirstate.hasdir' call from an empty `dirs` cache
1187 """benchmap a 'dirstate.hasdir' call from an empty `dirs` cache
1187 """
1188 """
1188 opts = _byteskwargs(opts)
1189 opts = _byteskwargs(opts)
1189 timer, fm = gettimer(ui, opts)
1190 timer, fm = gettimer(ui, opts)
1190 repo.dirstate.hasdir(b"a")
1191 repo.dirstate.hasdir(b"a")
1191
1192
1192 def setup():
1193 def setup():
1193 del repo.dirstate._map._dirs
1194 del repo.dirstate._map._dirs
1194
1195
1195 def d():
1196 def d():
1196 repo.dirstate.hasdir(b"a")
1197 repo.dirstate.hasdir(b"a")
1197
1198
1198 timer(d, setup=setup)
1199 timer(d, setup=setup)
1199 fm.end()
1200 fm.end()
1200
1201
1201
1202
1202 @command(b'perfdirstatefoldmap', formatteropts)
1203 @command(b'perfdirstatefoldmap', formatteropts)
1203 def perfdirstatefoldmap(ui, repo, **opts):
1204 def perfdirstatefoldmap(ui, repo, **opts):
1204 """benchmap a `dirstate._map.filefoldmap.get()` request
1205 """benchmap a `dirstate._map.filefoldmap.get()` request
1205
1206
1206 The dirstate filefoldmap cache is dropped between every request.
1207 The dirstate filefoldmap cache is dropped between every request.
1207 """
1208 """
1208 opts = _byteskwargs(opts)
1209 opts = _byteskwargs(opts)
1209 timer, fm = gettimer(ui, opts)
1210 timer, fm = gettimer(ui, opts)
1210 dirstate = repo.dirstate
1211 dirstate = repo.dirstate
1211 dirstate._map.filefoldmap.get(b'a')
1212 dirstate._map.filefoldmap.get(b'a')
1212
1213
1213 def setup():
1214 def setup():
1214 del dirstate._map.filefoldmap
1215 del dirstate._map.filefoldmap
1215
1216
1216 def d():
1217 def d():
1217 dirstate._map.filefoldmap.get(b'a')
1218 dirstate._map.filefoldmap.get(b'a')
1218
1219
1219 timer(d, setup=setup)
1220 timer(d, setup=setup)
1220 fm.end()
1221 fm.end()
1221
1222
1222
1223
1223 @command(b'perfdirfoldmap', formatteropts)
1224 @command(b'perfdirfoldmap', formatteropts)
1224 def perfdirfoldmap(ui, repo, **opts):
1225 def perfdirfoldmap(ui, repo, **opts):
1225 """benchmap a `dirstate._map.dirfoldmap.get()` request
1226 """benchmap a `dirstate._map.dirfoldmap.get()` request
1226
1227
1227 The dirstate dirfoldmap cache is dropped between every request.
1228 The dirstate dirfoldmap cache is dropped between every request.
1228 """
1229 """
1229 opts = _byteskwargs(opts)
1230 opts = _byteskwargs(opts)
1230 timer, fm = gettimer(ui, opts)
1231 timer, fm = gettimer(ui, opts)
1231 dirstate = repo.dirstate
1232 dirstate = repo.dirstate
1232 dirstate._map.dirfoldmap.get(b'a')
1233 dirstate._map.dirfoldmap.get(b'a')
1233
1234
1234 def setup():
1235 def setup():
1235 del dirstate._map.dirfoldmap
1236 del dirstate._map.dirfoldmap
1236 del dirstate._map._dirs
1237 del dirstate._map._dirs
1237
1238
1238 def d():
1239 def d():
1239 dirstate._map.dirfoldmap.get(b'a')
1240 dirstate._map.dirfoldmap.get(b'a')
1240
1241
1241 timer(d, setup=setup)
1242 timer(d, setup=setup)
1242 fm.end()
1243 fm.end()
1243
1244
1244
1245
1245 @command(b'perfdirstatewrite', formatteropts)
1246 @command(b'perfdirstatewrite', formatteropts)
1246 def perfdirstatewrite(ui, repo, **opts):
1247 def perfdirstatewrite(ui, repo, **opts):
1247 """benchmap the time it take to write a dirstate on disk
1248 """benchmap the time it take to write a dirstate on disk
1248 """
1249 """
1249 opts = _byteskwargs(opts)
1250 opts = _byteskwargs(opts)
1250 timer, fm = gettimer(ui, opts)
1251 timer, fm = gettimer(ui, opts)
1251 ds = repo.dirstate
1252 ds = repo.dirstate
1252 b"a" in ds
1253 b"a" in ds
1253
1254
1254 def setup():
1255 def setup():
1255 ds._dirty = True
1256 ds._dirty = True
1256
1257
1257 def d():
1258 def d():
1258 ds.write(repo.currenttransaction())
1259 ds.write(repo.currenttransaction())
1259
1260
1260 timer(d, setup=setup)
1261 timer(d, setup=setup)
1261 fm.end()
1262 fm.end()
1262
1263
1263
1264
1264 def _getmergerevs(repo, opts):
1265 def _getmergerevs(repo, opts):
1265 """parse command argument to return rev involved in merge
1266 """parse command argument to return rev involved in merge
1266
1267
1267 input: options dictionnary with `rev`, `from` and `bse`
1268 input: options dictionnary with `rev`, `from` and `bse`
1268 output: (localctx, otherctx, basectx)
1269 output: (localctx, otherctx, basectx)
1269 """
1270 """
1270 if opts[b'from']:
1271 if opts[b'from']:
1271 fromrev = scmutil.revsingle(repo, opts[b'from'])
1272 fromrev = scmutil.revsingle(repo, opts[b'from'])
1272 wctx = repo[fromrev]
1273 wctx = repo[fromrev]
1273 else:
1274 else:
1274 wctx = repo[None]
1275 wctx = repo[None]
1275 # we don't want working dir files to be stat'd in the benchmark, so
1276 # we don't want working dir files to be stat'd in the benchmark, so
1276 # prime that cache
1277 # prime that cache
1277 wctx.dirty()
1278 wctx.dirty()
1278 rctx = scmutil.revsingle(repo, opts[b'rev'], opts[b'rev'])
1279 rctx = scmutil.revsingle(repo, opts[b'rev'], opts[b'rev'])
1279 if opts[b'base']:
1280 if opts[b'base']:
1280 fromrev = scmutil.revsingle(repo, opts[b'base'])
1281 fromrev = scmutil.revsingle(repo, opts[b'base'])
1281 ancestor = repo[fromrev]
1282 ancestor = repo[fromrev]
1282 else:
1283 else:
1283 ancestor = wctx.ancestor(rctx)
1284 ancestor = wctx.ancestor(rctx)
1284 return (wctx, rctx, ancestor)
1285 return (wctx, rctx, ancestor)
1285
1286
1286
1287
1287 @command(
1288 @command(
1288 b'perfmergecalculate',
1289 b'perfmergecalculate',
1289 [
1290 [
1290 (b'r', b'rev', b'.', b'rev to merge against'),
1291 (b'r', b'rev', b'.', b'rev to merge against'),
1291 (b'', b'from', b'', b'rev to merge from'),
1292 (b'', b'from', b'', b'rev to merge from'),
1292 (b'', b'base', b'', b'the revision to use as base'),
1293 (b'', b'base', b'', b'the revision to use as base'),
1293 ]
1294 ]
1294 + formatteropts,
1295 + formatteropts,
1295 )
1296 )
1296 def perfmergecalculate(ui, repo, **opts):
1297 def perfmergecalculate(ui, repo, **opts):
1297 opts = _byteskwargs(opts)
1298 opts = _byteskwargs(opts)
1298 timer, fm = gettimer(ui, opts)
1299 timer, fm = gettimer(ui, opts)
1299
1300
1300 wctx, rctx, ancestor = _getmergerevs(repo, opts)
1301 wctx, rctx, ancestor = _getmergerevs(repo, opts)
1301
1302
1302 def d():
1303 def d():
1303 # acceptremote is True because we don't want prompts in the middle of
1304 # acceptremote is True because we don't want prompts in the middle of
1304 # our benchmark
1305 # our benchmark
1305 merge.calculateupdates(
1306 merge.calculateupdates(
1306 repo,
1307 repo,
1307 wctx,
1308 wctx,
1308 rctx,
1309 rctx,
1309 [ancestor],
1310 [ancestor],
1310 branchmerge=False,
1311 branchmerge=False,
1311 force=False,
1312 force=False,
1312 acceptremote=True,
1313 acceptremote=True,
1313 followcopies=True,
1314 followcopies=True,
1314 )
1315 )
1315
1316
1316 timer(d)
1317 timer(d)
1317 fm.end()
1318 fm.end()
1318
1319
1319
1320
1320 @command(
1321 @command(
1321 b'perfmergecopies',
1322 b'perfmergecopies',
1322 [
1323 [
1323 (b'r', b'rev', b'.', b'rev to merge against'),
1324 (b'r', b'rev', b'.', b'rev to merge against'),
1324 (b'', b'from', b'', b'rev to merge from'),
1325 (b'', b'from', b'', b'rev to merge from'),
1325 (b'', b'base', b'', b'the revision to use as base'),
1326 (b'', b'base', b'', b'the revision to use as base'),
1326 ]
1327 ]
1327 + formatteropts,
1328 + formatteropts,
1328 )
1329 )
1329 def perfmergecopies(ui, repo, **opts):
1330 def perfmergecopies(ui, repo, **opts):
1330 """measure runtime of `copies.mergecopies`"""
1331 """measure runtime of `copies.mergecopies`"""
1331 opts = _byteskwargs(opts)
1332 opts = _byteskwargs(opts)
1332 timer, fm = gettimer(ui, opts)
1333 timer, fm = gettimer(ui, opts)
1333 wctx, rctx, ancestor = _getmergerevs(repo, opts)
1334 wctx, rctx, ancestor = _getmergerevs(repo, opts)
1334
1335
1335 def d():
1336 def d():
1336 # acceptremote is True because we don't want prompts in the middle of
1337 # acceptremote is True because we don't want prompts in the middle of
1337 # our benchmark
1338 # our benchmark
1338 copies.mergecopies(repo, wctx, rctx, ancestor)
1339 copies.mergecopies(repo, wctx, rctx, ancestor)
1339
1340
1340 timer(d)
1341 timer(d)
1341 fm.end()
1342 fm.end()
1342
1343
1343
1344
1344 @command(b'perfpathcopies', [], b"REV REV")
1345 @command(b'perfpathcopies', [], b"REV REV")
1345 def perfpathcopies(ui, repo, rev1, rev2, **opts):
1346 def perfpathcopies(ui, repo, rev1, rev2, **opts):
1346 """benchmark the copy tracing logic"""
1347 """benchmark the copy tracing logic"""
1347 opts = _byteskwargs(opts)
1348 opts = _byteskwargs(opts)
1348 timer, fm = gettimer(ui, opts)
1349 timer, fm = gettimer(ui, opts)
1349 ctx1 = scmutil.revsingle(repo, rev1, rev1)
1350 ctx1 = scmutil.revsingle(repo, rev1, rev1)
1350 ctx2 = scmutil.revsingle(repo, rev2, rev2)
1351 ctx2 = scmutil.revsingle(repo, rev2, rev2)
1351
1352
1352 def d():
1353 def d():
1353 copies.pathcopies(ctx1, ctx2)
1354 copies.pathcopies(ctx1, ctx2)
1354
1355
1355 timer(d)
1356 timer(d)
1356 fm.end()
1357 fm.end()
1357
1358
1358
1359
1359 @command(
1360 @command(
1360 b'perfphases',
1361 b'perfphases',
1361 [(b'', b'full', False, b'include file reading time too'),],
1362 [(b'', b'full', False, b'include file reading time too'),],
1362 b"",
1363 b"",
1363 )
1364 )
1364 def perfphases(ui, repo, **opts):
1365 def perfphases(ui, repo, **opts):
1365 """benchmark phasesets computation"""
1366 """benchmark phasesets computation"""
1366 opts = _byteskwargs(opts)
1367 opts = _byteskwargs(opts)
1367 timer, fm = gettimer(ui, opts)
1368 timer, fm = gettimer(ui, opts)
1368 _phases = repo._phasecache
1369 _phases = repo._phasecache
1369 full = opts.get(b'full')
1370 full = opts.get(b'full')
1370
1371
1371 def d():
1372 def d():
1372 phases = _phases
1373 phases = _phases
1373 if full:
1374 if full:
1374 clearfilecache(repo, b'_phasecache')
1375 clearfilecache(repo, b'_phasecache')
1375 phases = repo._phasecache
1376 phases = repo._phasecache
1376 phases.invalidate()
1377 phases.invalidate()
1377 phases.loadphaserevs(repo)
1378 phases.loadphaserevs(repo)
1378
1379
1379 timer(d)
1380 timer(d)
1380 fm.end()
1381 fm.end()
1381
1382
1382
1383
1383 @command(b'perfphasesremote', [], b"[DEST]")
1384 @command(b'perfphasesremote', [], b"[DEST]")
1384 def perfphasesremote(ui, repo, dest=None, **opts):
1385 def perfphasesremote(ui, repo, dest=None, **opts):
1385 """benchmark time needed to analyse phases of the remote server"""
1386 """benchmark time needed to analyse phases of the remote server"""
1386 from mercurial.node import bin
1387 from mercurial.node import bin
1387 from mercurial import (
1388 from mercurial import (
1388 exchange,
1389 exchange,
1389 hg,
1390 hg,
1390 phases,
1391 phases,
1391 )
1392 )
1392
1393
1393 opts = _byteskwargs(opts)
1394 opts = _byteskwargs(opts)
1394 timer, fm = gettimer(ui, opts)
1395 timer, fm = gettimer(ui, opts)
1395
1396
1396 path = ui.paths.getpath(dest, default=(b'default-push', b'default'))
1397 path = ui.paths.getpath(dest, default=(b'default-push', b'default'))
1397 if not path:
1398 if not path:
1398 raise error.Abort(
1399 raise error.Abort(
1399 b'default repository not configured!',
1400 b'default repository not configured!',
1400 hint=b"see 'hg help config.paths'",
1401 hint=b"see 'hg help config.paths'",
1401 )
1402 )
1402 dest = path.pushloc or path.loc
1403 dest = path.pushloc or path.loc
1403 ui.statusnoi18n(b'analysing phase of %s\n' % util.hidepassword(dest))
1404 ui.statusnoi18n(b'analysing phase of %s\n' % util.hidepassword(dest))
1404 other = hg.peer(repo, opts, dest)
1405 other = hg.peer(repo, opts, dest)
1405
1406
1406 # easier to perform discovery through the operation
1407 # easier to perform discovery through the operation
1407 op = exchange.pushoperation(repo, other)
1408 op = exchange.pushoperation(repo, other)
1408 exchange._pushdiscoverychangeset(op)
1409 exchange._pushdiscoverychangeset(op)
1409
1410
1410 remotesubset = op.fallbackheads
1411 remotesubset = op.fallbackheads
1411
1412
1412 with other.commandexecutor() as e:
1413 with other.commandexecutor() as e:
1413 remotephases = e.callcommand(
1414 remotephases = e.callcommand(
1414 b'listkeys', {b'namespace': b'phases'}
1415 b'listkeys', {b'namespace': b'phases'}
1415 ).result()
1416 ).result()
1416 del other
1417 del other
1417 publishing = remotephases.get(b'publishing', False)
1418 publishing = remotephases.get(b'publishing', False)
1418 if publishing:
1419 if publishing:
1419 ui.statusnoi18n(b'publishing: yes\n')
1420 ui.statusnoi18n(b'publishing: yes\n')
1420 else:
1421 else:
1421 ui.statusnoi18n(b'publishing: no\n')
1422 ui.statusnoi18n(b'publishing: no\n')
1422
1423
1423 nodemap = repo.changelog.nodemap
1424 nodemap = repo.changelog.nodemap
1424 nonpublishroots = 0
1425 nonpublishroots = 0
1425 for nhex, phase in remotephases.iteritems():
1426 for nhex, phase in remotephases.iteritems():
1426 if nhex == b'publishing': # ignore data related to publish option
1427 if nhex == b'publishing': # ignore data related to publish option
1427 continue
1428 continue
1428 node = bin(nhex)
1429 node = bin(nhex)
1429 if node in nodemap and int(phase):
1430 if node in nodemap and int(phase):
1430 nonpublishroots += 1
1431 nonpublishroots += 1
1431 ui.statusnoi18n(b'number of roots: %d\n' % len(remotephases))
1432 ui.statusnoi18n(b'number of roots: %d\n' % len(remotephases))
1432 ui.statusnoi18n(b'number of known non public roots: %d\n' % nonpublishroots)
1433 ui.statusnoi18n(b'number of known non public roots: %d\n' % nonpublishroots)
1433
1434
1434 def d():
1435 def d():
1435 phases.remotephasessummary(repo, remotesubset, remotephases)
1436 phases.remotephasessummary(repo, remotesubset, remotephases)
1436
1437
1437 timer(d)
1438 timer(d)
1438 fm.end()
1439 fm.end()
1439
1440
1440
1441
1441 @command(
1442 @command(
1442 b'perfmanifest',
1443 b'perfmanifest',
1443 [
1444 [
1444 (b'm', b'manifest-rev', False, b'Look up a manifest node revision'),
1445 (b'm', b'manifest-rev', False, b'Look up a manifest node revision'),
1445 (b'', b'clear-disk', False, b'clear on-disk caches too'),
1446 (b'', b'clear-disk', False, b'clear on-disk caches too'),
1446 ]
1447 ]
1447 + formatteropts,
1448 + formatteropts,
1448 b'REV|NODE',
1449 b'REV|NODE',
1449 )
1450 )
1450 def perfmanifest(ui, repo, rev, manifest_rev=False, clear_disk=False, **opts):
1451 def perfmanifest(ui, repo, rev, manifest_rev=False, clear_disk=False, **opts):
1451 """benchmark the time to read a manifest from disk and return a usable
1452 """benchmark the time to read a manifest from disk and return a usable
1452 dict-like object
1453 dict-like object
1453
1454
1454 Manifest caches are cleared before retrieval."""
1455 Manifest caches are cleared before retrieval."""
1455 opts = _byteskwargs(opts)
1456 opts = _byteskwargs(opts)
1456 timer, fm = gettimer(ui, opts)
1457 timer, fm = gettimer(ui, opts)
1457 if not manifest_rev:
1458 if not manifest_rev:
1458 ctx = scmutil.revsingle(repo, rev, rev)
1459 ctx = scmutil.revsingle(repo, rev, rev)
1459 t = ctx.manifestnode()
1460 t = ctx.manifestnode()
1460 else:
1461 else:
1461 from mercurial.node import bin
1462 from mercurial.node import bin
1462
1463
1463 if len(rev) == 40:
1464 if len(rev) == 40:
1464 t = bin(rev)
1465 t = bin(rev)
1465 else:
1466 else:
1466 try:
1467 try:
1467 rev = int(rev)
1468 rev = int(rev)
1468
1469
1469 if util.safehasattr(repo.manifestlog, b'getstorage'):
1470 if util.safehasattr(repo.manifestlog, b'getstorage'):
1470 t = repo.manifestlog.getstorage(b'').node(rev)
1471 t = repo.manifestlog.getstorage(b'').node(rev)
1471 else:
1472 else:
1472 t = repo.manifestlog._revlog.lookup(rev)
1473 t = repo.manifestlog._revlog.lookup(rev)
1473 except ValueError:
1474 except ValueError:
1474 raise error.Abort(
1475 raise error.Abort(
1475 b'manifest revision must be integer or full node'
1476 b'manifest revision must be integer or full node'
1476 )
1477 )
1477
1478
1478 def d():
1479 def d():
1479 repo.manifestlog.clearcaches(clear_persisted_data=clear_disk)
1480 repo.manifestlog.clearcaches(clear_persisted_data=clear_disk)
1480 repo.manifestlog[t].read()
1481 repo.manifestlog[t].read()
1481
1482
1482 timer(d)
1483 timer(d)
1483 fm.end()
1484 fm.end()
1484
1485
1485
1486
1486 @command(b'perfchangeset', formatteropts)
1487 @command(b'perfchangeset', formatteropts)
1487 def perfchangeset(ui, repo, rev, **opts):
1488 def perfchangeset(ui, repo, rev, **opts):
1488 opts = _byteskwargs(opts)
1489 opts = _byteskwargs(opts)
1489 timer, fm = gettimer(ui, opts)
1490 timer, fm = gettimer(ui, opts)
1490 n = scmutil.revsingle(repo, rev).node()
1491 n = scmutil.revsingle(repo, rev).node()
1491
1492
1492 def d():
1493 def d():
1493 repo.changelog.read(n)
1494 repo.changelog.read(n)
1494 # repo.changelog._cache = None
1495 # repo.changelog._cache = None
1495
1496
1496 timer(d)
1497 timer(d)
1497 fm.end()
1498 fm.end()
1498
1499
1499
1500
1500 @command(b'perfignore', formatteropts)
1501 @command(b'perfignore', formatteropts)
1501 def perfignore(ui, repo, **opts):
1502 def perfignore(ui, repo, **opts):
1502 """benchmark operation related to computing ignore"""
1503 """benchmark operation related to computing ignore"""
1503 opts = _byteskwargs(opts)
1504 opts = _byteskwargs(opts)
1504 timer, fm = gettimer(ui, opts)
1505 timer, fm = gettimer(ui, opts)
1505 dirstate = repo.dirstate
1506 dirstate = repo.dirstate
1506
1507
1507 def setupone():
1508 def setupone():
1508 dirstate.invalidate()
1509 dirstate.invalidate()
1509 clearfilecache(dirstate, b'_ignore')
1510 clearfilecache(dirstate, b'_ignore')
1510
1511
1511 def runone():
1512 def runone():
1512 dirstate._ignore
1513 dirstate._ignore
1513
1514
1514 timer(runone, setup=setupone, title=b"load")
1515 timer(runone, setup=setupone, title=b"load")
1515 fm.end()
1516 fm.end()
1516
1517
1517
1518
1518 @command(
1519 @command(
1519 b'perfindex',
1520 b'perfindex',
1520 [
1521 [
1521 (b'', b'rev', [], b'revision to be looked up (default tip)'),
1522 (b'', b'rev', [], b'revision to be looked up (default tip)'),
1522 (b'', b'no-lookup', None, b'do not revision lookup post creation'),
1523 (b'', b'no-lookup', None, b'do not revision lookup post creation'),
1523 ]
1524 ]
1524 + formatteropts,
1525 + formatteropts,
1525 )
1526 )
1526 def perfindex(ui, repo, **opts):
1527 def perfindex(ui, repo, **opts):
1527 """benchmark index creation time followed by a lookup
1528 """benchmark index creation time followed by a lookup
1528
1529
1529 The default is to look `tip` up. Depending on the index implementation,
1530 The default is to look `tip` up. Depending on the index implementation,
1530 the revision looked up can matters. For example, an implementation
1531 the revision looked up can matters. For example, an implementation
1531 scanning the index will have a faster lookup time for `--rev tip` than for
1532 scanning the index will have a faster lookup time for `--rev tip` than for
1532 `--rev 0`. The number of looked up revisions and their order can also
1533 `--rev 0`. The number of looked up revisions and their order can also
1533 matters.
1534 matters.
1534
1535
1535 Example of useful set to test:
1536 Example of useful set to test:
1536 * tip
1537 * tip
1537 * 0
1538 * 0
1538 * -10:
1539 * -10:
1539 * :10
1540 * :10
1540 * -10: + :10
1541 * -10: + :10
1541 * :10: + -10:
1542 * :10: + -10:
1542 * -10000:
1543 * -10000:
1543 * -10000: + 0
1544 * -10000: + 0
1544
1545
1545 It is not currently possible to check for lookup of a missing node. For
1546 It is not currently possible to check for lookup of a missing node. For
1546 deeper lookup benchmarking, checkout the `perfnodemap` command."""
1547 deeper lookup benchmarking, checkout the `perfnodemap` command."""
1547 import mercurial.revlog
1548 import mercurial.revlog
1548
1549
1549 opts = _byteskwargs(opts)
1550 opts = _byteskwargs(opts)
1550 timer, fm = gettimer(ui, opts)
1551 timer, fm = gettimer(ui, opts)
1551 mercurial.revlog._prereadsize = 2 ** 24 # disable lazy parser in old hg
1552 mercurial.revlog._prereadsize = 2 ** 24 # disable lazy parser in old hg
1552 if opts[b'no_lookup']:
1553 if opts[b'no_lookup']:
1553 if opts['rev']:
1554 if opts['rev']:
1554 raise error.Abort('--no-lookup and --rev are mutually exclusive')
1555 raise error.Abort('--no-lookup and --rev are mutually exclusive')
1555 nodes = []
1556 nodes = []
1556 elif not opts[b'rev']:
1557 elif not opts[b'rev']:
1557 nodes = [repo[b"tip"].node()]
1558 nodes = [repo[b"tip"].node()]
1558 else:
1559 else:
1559 revs = scmutil.revrange(repo, opts[b'rev'])
1560 revs = scmutil.revrange(repo, opts[b'rev'])
1560 cl = repo.changelog
1561 cl = repo.changelog
1561 nodes = [cl.node(r) for r in revs]
1562 nodes = [cl.node(r) for r in revs]
1562
1563
1563 unfi = repo.unfiltered()
1564 unfi = repo.unfiltered()
1564 # find the filecache func directly
1565 # find the filecache func directly
1565 # This avoid polluting the benchmark with the filecache logic
1566 # This avoid polluting the benchmark with the filecache logic
1566 makecl = unfi.__class__.changelog.func
1567 makecl = unfi.__class__.changelog.func
1567
1568
1568 def setup():
1569 def setup():
1569 # probably not necessary, but for good measure
1570 # probably not necessary, but for good measure
1570 clearchangelog(unfi)
1571 clearchangelog(unfi)
1571
1572
1572 def d():
1573 def d():
1573 cl = makecl(unfi)
1574 cl = makecl(unfi)
1574 for n in nodes:
1575 for n in nodes:
1575 cl.rev(n)
1576 cl.rev(n)
1576
1577
1577 timer(d, setup=setup)
1578 timer(d, setup=setup)
1578 fm.end()
1579 fm.end()
1579
1580
1580
1581
1581 @command(
1582 @command(
1582 b'perfnodemap',
1583 b'perfnodemap',
1583 [
1584 [
1584 (b'', b'rev', [], b'revision to be looked up (default tip)'),
1585 (b'', b'rev', [], b'revision to be looked up (default tip)'),
1585 (b'', b'clear-caches', True, b'clear revlog cache between calls'),
1586 (b'', b'clear-caches', True, b'clear revlog cache between calls'),
1586 ]
1587 ]
1587 + formatteropts,
1588 + formatteropts,
1588 )
1589 )
1589 def perfnodemap(ui, repo, **opts):
1590 def perfnodemap(ui, repo, **opts):
1590 """benchmark the time necessary to look up revision from a cold nodemap
1591 """benchmark the time necessary to look up revision from a cold nodemap
1591
1592
1592 Depending on the implementation, the amount and order of revision we look
1593 Depending on the implementation, the amount and order of revision we look
1593 up can varies. Example of useful set to test:
1594 up can varies. Example of useful set to test:
1594 * tip
1595 * tip
1595 * 0
1596 * 0
1596 * -10:
1597 * -10:
1597 * :10
1598 * :10
1598 * -10: + :10
1599 * -10: + :10
1599 * :10: + -10:
1600 * :10: + -10:
1600 * -10000:
1601 * -10000:
1601 * -10000: + 0
1602 * -10000: + 0
1602
1603
1603 The command currently focus on valid binary lookup. Benchmarking for
1604 The command currently focus on valid binary lookup. Benchmarking for
1604 hexlookup, prefix lookup and missing lookup would also be valuable.
1605 hexlookup, prefix lookup and missing lookup would also be valuable.
1605 """
1606 """
1606 import mercurial.revlog
1607 import mercurial.revlog
1607
1608
1608 opts = _byteskwargs(opts)
1609 opts = _byteskwargs(opts)
1609 timer, fm = gettimer(ui, opts)
1610 timer, fm = gettimer(ui, opts)
1610 mercurial.revlog._prereadsize = 2 ** 24 # disable lazy parser in old hg
1611 mercurial.revlog._prereadsize = 2 ** 24 # disable lazy parser in old hg
1611
1612
1612 unfi = repo.unfiltered()
1613 unfi = repo.unfiltered()
1613 clearcaches = opts['clear_caches']
1614 clearcaches = opts['clear_caches']
1614 # find the filecache func directly
1615 # find the filecache func directly
1615 # This avoid polluting the benchmark with the filecache logic
1616 # This avoid polluting the benchmark with the filecache logic
1616 makecl = unfi.__class__.changelog.func
1617 makecl = unfi.__class__.changelog.func
1617 if not opts[b'rev']:
1618 if not opts[b'rev']:
1618 raise error.Abort('use --rev to specify revisions to look up')
1619 raise error.Abort('use --rev to specify revisions to look up')
1619 revs = scmutil.revrange(repo, opts[b'rev'])
1620 revs = scmutil.revrange(repo, opts[b'rev'])
1620 cl = repo.changelog
1621 cl = repo.changelog
1621 nodes = [cl.node(r) for r in revs]
1622 nodes = [cl.node(r) for r in revs]
1622
1623
1623 # use a list to pass reference to a nodemap from one closure to the next
1624 # use a list to pass reference to a nodemap from one closure to the next
1624 nodeget = [None]
1625 nodeget = [None]
1625
1626
1626 def setnodeget():
1627 def setnodeget():
1627 # probably not necessary, but for good measure
1628 # probably not necessary, but for good measure
1628 clearchangelog(unfi)
1629 clearchangelog(unfi)
1629 nodeget[0] = makecl(unfi).nodemap.get
1630 nodeget[0] = makecl(unfi).nodemap.get
1630
1631
1631 def d():
1632 def d():
1632 get = nodeget[0]
1633 get = nodeget[0]
1633 for n in nodes:
1634 for n in nodes:
1634 get(n)
1635 get(n)
1635
1636
1636 setup = None
1637 setup = None
1637 if clearcaches:
1638 if clearcaches:
1638
1639
1639 def setup():
1640 def setup():
1640 setnodeget()
1641 setnodeget()
1641
1642
1642 else:
1643 else:
1643 setnodeget()
1644 setnodeget()
1644 d() # prewarm the data structure
1645 d() # prewarm the data structure
1645 timer(d, setup=setup)
1646 timer(d, setup=setup)
1646 fm.end()
1647 fm.end()
1647
1648
1648
1649
1649 @command(b'perfstartup', formatteropts)
1650 @command(b'perfstartup', formatteropts)
1650 def perfstartup(ui, repo, **opts):
1651 def perfstartup(ui, repo, **opts):
1651 opts = _byteskwargs(opts)
1652 opts = _byteskwargs(opts)
1652 timer, fm = gettimer(ui, opts)
1653 timer, fm = gettimer(ui, opts)
1653
1654
1654 def d():
1655 def d():
1655 if os.name != 'nt':
1656 if os.name != 'nt':
1656 os.system(
1657 os.system(
1657 b"HGRCPATH= %s version -q > /dev/null" % fsencode(sys.argv[0])
1658 b"HGRCPATH= %s version -q > /dev/null" % fsencode(sys.argv[0])
1658 )
1659 )
1659 else:
1660 else:
1660 os.environ['HGRCPATH'] = r' '
1661 os.environ['HGRCPATH'] = r' '
1661 os.system("%s version -q > NUL" % sys.argv[0])
1662 os.system("%s version -q > NUL" % sys.argv[0])
1662
1663
1663 timer(d)
1664 timer(d)
1664 fm.end()
1665 fm.end()
1665
1666
1666
1667
1667 @command(b'perfparents', formatteropts)
1668 @command(b'perfparents', formatteropts)
1668 def perfparents(ui, repo, **opts):
1669 def perfparents(ui, repo, **opts):
1669 """benchmark the time necessary to fetch one changeset's parents.
1670 """benchmark the time necessary to fetch one changeset's parents.
1670
1671
1671 The fetch is done using the `node identifier`, traversing all object layers
1672 The fetch is done using the `node identifier`, traversing all object layers
1672 from the repository object. The first N revisions will be used for this
1673 from the repository object. The first N revisions will be used for this
1673 benchmark. N is controlled by the ``perf.parentscount`` config option
1674 benchmark. N is controlled by the ``perf.parentscount`` config option
1674 (default: 1000).
1675 (default: 1000).
1675 """
1676 """
1676 opts = _byteskwargs(opts)
1677 opts = _byteskwargs(opts)
1677 timer, fm = gettimer(ui, opts)
1678 timer, fm = gettimer(ui, opts)
1678 # control the number of commits perfparents iterates over
1679 # control the number of commits perfparents iterates over
1679 # experimental config: perf.parentscount
1680 # experimental config: perf.parentscount
1680 count = getint(ui, b"perf", b"parentscount", 1000)
1681 count = getint(ui, b"perf", b"parentscount", 1000)
1681 if len(repo.changelog) < count:
1682 if len(repo.changelog) < count:
1682 raise error.Abort(b"repo needs %d commits for this test" % count)
1683 raise error.Abort(b"repo needs %d commits for this test" % count)
1683 repo = repo.unfiltered()
1684 repo = repo.unfiltered()
1684 nl = [repo.changelog.node(i) for i in _xrange(count)]
1685 nl = [repo.changelog.node(i) for i in _xrange(count)]
1685
1686
1686 def d():
1687 def d():
1687 for n in nl:
1688 for n in nl:
1688 repo.changelog.parents(n)
1689 repo.changelog.parents(n)
1689
1690
1690 timer(d)
1691 timer(d)
1691 fm.end()
1692 fm.end()
1692
1693
1693
1694
1694 @command(b'perfctxfiles', formatteropts)
1695 @command(b'perfctxfiles', formatteropts)
1695 def perfctxfiles(ui, repo, x, **opts):
1696 def perfctxfiles(ui, repo, x, **opts):
1696 opts = _byteskwargs(opts)
1697 opts = _byteskwargs(opts)
1697 x = int(x)
1698 x = int(x)
1698 timer, fm = gettimer(ui, opts)
1699 timer, fm = gettimer(ui, opts)
1699
1700
1700 def d():
1701 def d():
1701 len(repo[x].files())
1702 len(repo[x].files())
1702
1703
1703 timer(d)
1704 timer(d)
1704 fm.end()
1705 fm.end()
1705
1706
1706
1707
1707 @command(b'perfrawfiles', formatteropts)
1708 @command(b'perfrawfiles', formatteropts)
1708 def perfrawfiles(ui, repo, x, **opts):
1709 def perfrawfiles(ui, repo, x, **opts):
1709 opts = _byteskwargs(opts)
1710 opts = _byteskwargs(opts)
1710 x = int(x)
1711 x = int(x)
1711 timer, fm = gettimer(ui, opts)
1712 timer, fm = gettimer(ui, opts)
1712 cl = repo.changelog
1713 cl = repo.changelog
1713
1714
1714 def d():
1715 def d():
1715 len(cl.read(x)[3])
1716 len(cl.read(x)[3])
1716
1717
1717 timer(d)
1718 timer(d)
1718 fm.end()
1719 fm.end()
1719
1720
1720
1721
1721 @command(b'perflookup', formatteropts)
1722 @command(b'perflookup', formatteropts)
1722 def perflookup(ui, repo, rev, **opts):
1723 def perflookup(ui, repo, rev, **opts):
1723 opts = _byteskwargs(opts)
1724 opts = _byteskwargs(opts)
1724 timer, fm = gettimer(ui, opts)
1725 timer, fm = gettimer(ui, opts)
1725 timer(lambda: len(repo.lookup(rev)))
1726 timer(lambda: len(repo.lookup(rev)))
1726 fm.end()
1727 fm.end()
1727
1728
1728
1729
1729 @command(
1730 @command(
1730 b'perflinelogedits',
1731 b'perflinelogedits',
1731 [
1732 [
1732 (b'n', b'edits', 10000, b'number of edits'),
1733 (b'n', b'edits', 10000, b'number of edits'),
1733 (b'', b'max-hunk-lines', 10, b'max lines in a hunk'),
1734 (b'', b'max-hunk-lines', 10, b'max lines in a hunk'),
1734 ],
1735 ],
1735 norepo=True,
1736 norepo=True,
1736 )
1737 )
1737 def perflinelogedits(ui, **opts):
1738 def perflinelogedits(ui, **opts):
1738 from mercurial import linelog
1739 from mercurial import linelog
1739
1740
1740 opts = _byteskwargs(opts)
1741 opts = _byteskwargs(opts)
1741
1742
1742 edits = opts[b'edits']
1743 edits = opts[b'edits']
1743 maxhunklines = opts[b'max_hunk_lines']
1744 maxhunklines = opts[b'max_hunk_lines']
1744
1745
1745 maxb1 = 100000
1746 maxb1 = 100000
1746 random.seed(0)
1747 random.seed(0)
1747 randint = random.randint
1748 randint = random.randint
1748 currentlines = 0
1749 currentlines = 0
1749 arglist = []
1750 arglist = []
1750 for rev in _xrange(edits):
1751 for rev in _xrange(edits):
1751 a1 = randint(0, currentlines)
1752 a1 = randint(0, currentlines)
1752 a2 = randint(a1, min(currentlines, a1 + maxhunklines))
1753 a2 = randint(a1, min(currentlines, a1 + maxhunklines))
1753 b1 = randint(0, maxb1)
1754 b1 = randint(0, maxb1)
1754 b2 = randint(b1, b1 + maxhunklines)
1755 b2 = randint(b1, b1 + maxhunklines)
1755 currentlines += (b2 - b1) - (a2 - a1)
1756 currentlines += (b2 - b1) - (a2 - a1)
1756 arglist.append((rev, a1, a2, b1, b2))
1757 arglist.append((rev, a1, a2, b1, b2))
1757
1758
1758 def d():
1759 def d():
1759 ll = linelog.linelog()
1760 ll = linelog.linelog()
1760 for args in arglist:
1761 for args in arglist:
1761 ll.replacelines(*args)
1762 ll.replacelines(*args)
1762
1763
1763 timer, fm = gettimer(ui, opts)
1764 timer, fm = gettimer(ui, opts)
1764 timer(d)
1765 timer(d)
1765 fm.end()
1766 fm.end()
1766
1767
1767
1768
1768 @command(b'perfrevrange', formatteropts)
1769 @command(b'perfrevrange', formatteropts)
1769 def perfrevrange(ui, repo, *specs, **opts):
1770 def perfrevrange(ui, repo, *specs, **opts):
1770 opts = _byteskwargs(opts)
1771 opts = _byteskwargs(opts)
1771 timer, fm = gettimer(ui, opts)
1772 timer, fm = gettimer(ui, opts)
1772 revrange = scmutil.revrange
1773 revrange = scmutil.revrange
1773 timer(lambda: len(revrange(repo, specs)))
1774 timer(lambda: len(revrange(repo, specs)))
1774 fm.end()
1775 fm.end()
1775
1776
1776
1777
1777 @command(b'perfnodelookup', formatteropts)
1778 @command(b'perfnodelookup', formatteropts)
1778 def perfnodelookup(ui, repo, rev, **opts):
1779 def perfnodelookup(ui, repo, rev, **opts):
1779 opts = _byteskwargs(opts)
1780 opts = _byteskwargs(opts)
1780 timer, fm = gettimer(ui, opts)
1781 timer, fm = gettimer(ui, opts)
1781 import mercurial.revlog
1782 import mercurial.revlog
1782
1783
1783 mercurial.revlog._prereadsize = 2 ** 24 # disable lazy parser in old hg
1784 mercurial.revlog._prereadsize = 2 ** 24 # disable lazy parser in old hg
1784 n = scmutil.revsingle(repo, rev).node()
1785 n = scmutil.revsingle(repo, rev).node()
1785 cl = mercurial.revlog.revlog(getsvfs(repo), b"00changelog.i")
1786 cl = mercurial.revlog.revlog(getsvfs(repo), b"00changelog.i")
1786
1787
1787 def d():
1788 def d():
1788 cl.rev(n)
1789 cl.rev(n)
1789 clearcaches(cl)
1790 clearcaches(cl)
1790
1791
1791 timer(d)
1792 timer(d)
1792 fm.end()
1793 fm.end()
1793
1794
1794
1795
1795 @command(
1796 @command(
1796 b'perflog',
1797 b'perflog',
1797 [(b'', b'rename', False, b'ask log to follow renames')] + formatteropts,
1798 [(b'', b'rename', False, b'ask log to follow renames')] + formatteropts,
1798 )
1799 )
1799 def perflog(ui, repo, rev=None, **opts):
1800 def perflog(ui, repo, rev=None, **opts):
1800 opts = _byteskwargs(opts)
1801 opts = _byteskwargs(opts)
1801 if rev is None:
1802 if rev is None:
1802 rev = []
1803 rev = []
1803 timer, fm = gettimer(ui, opts)
1804 timer, fm = gettimer(ui, opts)
1804 ui.pushbuffer()
1805 ui.pushbuffer()
1805 timer(
1806 timer(
1806 lambda: commands.log(
1807 lambda: commands.log(
1807 ui, repo, rev=rev, date=b'', user=b'', copies=opts.get(b'rename')
1808 ui, repo, rev=rev, date=b'', user=b'', copies=opts.get(b'rename')
1808 )
1809 )
1809 )
1810 )
1810 ui.popbuffer()
1811 ui.popbuffer()
1811 fm.end()
1812 fm.end()
1812
1813
1813
1814
1814 @command(b'perfmoonwalk', formatteropts)
1815 @command(b'perfmoonwalk', formatteropts)
1815 def perfmoonwalk(ui, repo, **opts):
1816 def perfmoonwalk(ui, repo, **opts):
1816 """benchmark walking the changelog backwards
1817 """benchmark walking the changelog backwards
1817
1818
1818 This also loads the changelog data for each revision in the changelog.
1819 This also loads the changelog data for each revision in the changelog.
1819 """
1820 """
1820 opts = _byteskwargs(opts)
1821 opts = _byteskwargs(opts)
1821 timer, fm = gettimer(ui, opts)
1822 timer, fm = gettimer(ui, opts)
1822
1823
1823 def moonwalk():
1824 def moonwalk():
1824 for i in repo.changelog.revs(start=(len(repo) - 1), stop=-1):
1825 for i in repo.changelog.revs(start=(len(repo) - 1), stop=-1):
1825 ctx = repo[i]
1826 ctx = repo[i]
1826 ctx.branch() # read changelog data (in addition to the index)
1827 ctx.branch() # read changelog data (in addition to the index)
1827
1828
1828 timer(moonwalk)
1829 timer(moonwalk)
1829 fm.end()
1830 fm.end()
1830
1831
1831
1832
1832 @command(
1833 @command(
1833 b'perftemplating',
1834 b'perftemplating',
1834 [(b'r', b'rev', [], b'revisions to run the template on'),] + formatteropts,
1835 [(b'r', b'rev', [], b'revisions to run the template on'),] + formatteropts,
1835 )
1836 )
1836 def perftemplating(ui, repo, testedtemplate=None, **opts):
1837 def perftemplating(ui, repo, testedtemplate=None, **opts):
1837 """test the rendering time of a given template"""
1838 """test the rendering time of a given template"""
1838 if makelogtemplater is None:
1839 if makelogtemplater is None:
1839 raise error.Abort(
1840 raise error.Abort(
1840 b"perftemplating not available with this Mercurial",
1841 b"perftemplating not available with this Mercurial",
1841 hint=b"use 4.3 or later",
1842 hint=b"use 4.3 or later",
1842 )
1843 )
1843
1844
1844 opts = _byteskwargs(opts)
1845 opts = _byteskwargs(opts)
1845
1846
1846 nullui = ui.copy()
1847 nullui = ui.copy()
1847 nullui.fout = open(os.devnull, 'wb')
1848 nullui.fout = open(os.devnull, 'wb')
1848 nullui.disablepager()
1849 nullui.disablepager()
1849 revs = opts.get(b'rev')
1850 revs = opts.get(b'rev')
1850 if not revs:
1851 if not revs:
1851 revs = [b'all()']
1852 revs = [b'all()']
1852 revs = list(scmutil.revrange(repo, revs))
1853 revs = list(scmutil.revrange(repo, revs))
1853
1854
1854 defaulttemplate = (
1855 defaulttemplate = (
1855 b'{date|shortdate} [{rev}:{node|short}]'
1856 b'{date|shortdate} [{rev}:{node|short}]'
1856 b' {author|person}: {desc|firstline}\n'
1857 b' {author|person}: {desc|firstline}\n'
1857 )
1858 )
1858 if testedtemplate is None:
1859 if testedtemplate is None:
1859 testedtemplate = defaulttemplate
1860 testedtemplate = defaulttemplate
1860 displayer = makelogtemplater(nullui, repo, testedtemplate)
1861 displayer = makelogtemplater(nullui, repo, testedtemplate)
1861
1862
1862 def format():
1863 def format():
1863 for r in revs:
1864 for r in revs:
1864 ctx = repo[r]
1865 ctx = repo[r]
1865 displayer.show(ctx)
1866 displayer.show(ctx)
1866 displayer.flush(ctx)
1867 displayer.flush(ctx)
1867
1868
1868 timer, fm = gettimer(ui, opts)
1869 timer, fm = gettimer(ui, opts)
1869 timer(format)
1870 timer(format)
1870 fm.end()
1871 fm.end()
1871
1872
1872
1873
1873 def _displaystats(ui, opts, entries, data):
1874 def _displaystats(ui, opts, entries, data):
1874 pass
1875 pass
1875 # use a second formatter because the data are quite different, not sure
1876 # use a second formatter because the data are quite different, not sure
1876 # how it flies with the templater.
1877 # how it flies with the templater.
1877 fm = ui.formatter(b'perf-stats', opts)
1878 fm = ui.formatter(b'perf-stats', opts)
1878 for key, title in entries:
1879 for key, title in entries:
1879 values = data[key]
1880 values = data[key]
1880 nbvalues = len(data)
1881 nbvalues = len(data)
1881 values.sort()
1882 values.sort()
1882 stats = {
1883 stats = {
1883 'key': key,
1884 'key': key,
1884 'title': title,
1885 'title': title,
1885 'nbitems': len(values),
1886 'nbitems': len(values),
1886 'min': values[0][0],
1887 'min': values[0][0],
1887 '10%': values[(nbvalues * 10) // 100][0],
1888 '10%': values[(nbvalues * 10) // 100][0],
1888 '25%': values[(nbvalues * 25) // 100][0],
1889 '25%': values[(nbvalues * 25) // 100][0],
1889 '50%': values[(nbvalues * 50) // 100][0],
1890 '50%': values[(nbvalues * 50) // 100][0],
1890 '75%': values[(nbvalues * 75) // 100][0],
1891 '75%': values[(nbvalues * 75) // 100][0],
1891 '80%': values[(nbvalues * 80) // 100][0],
1892 '80%': values[(nbvalues * 80) // 100][0],
1892 '85%': values[(nbvalues * 85) // 100][0],
1893 '85%': values[(nbvalues * 85) // 100][0],
1893 '90%': values[(nbvalues * 90) // 100][0],
1894 '90%': values[(nbvalues * 90) // 100][0],
1894 '95%': values[(nbvalues * 95) // 100][0],
1895 '95%': values[(nbvalues * 95) // 100][0],
1895 '99%': values[(nbvalues * 99) // 100][0],
1896 '99%': values[(nbvalues * 99) // 100][0],
1896 'max': values[-1][0],
1897 'max': values[-1][0],
1897 }
1898 }
1898 fm.startitem()
1899 fm.startitem()
1899 fm.data(**stats)
1900 fm.data(**stats)
1900 # make node pretty for the human output
1901 # make node pretty for the human output
1901 fm.plain('### %s (%d items)\n' % (title, len(values)))
1902 fm.plain('### %s (%d items)\n' % (title, len(values)))
1902 lines = [
1903 lines = [
1903 'min',
1904 'min',
1904 '10%',
1905 '10%',
1905 '25%',
1906 '25%',
1906 '50%',
1907 '50%',
1907 '75%',
1908 '75%',
1908 '80%',
1909 '80%',
1909 '85%',
1910 '85%',
1910 '90%',
1911 '90%',
1911 '95%',
1912 '95%',
1912 '99%',
1913 '99%',
1913 'max',
1914 'max',
1914 ]
1915 ]
1915 for l in lines:
1916 for l in lines:
1916 fm.plain('%s: %s\n' % (l, stats[l]))
1917 fm.plain('%s: %s\n' % (l, stats[l]))
1917 fm.end()
1918 fm.end()
1918
1919
1919
1920
1920 @command(
1921 @command(
1921 b'perfhelper-mergecopies',
1922 b'perfhelper-mergecopies',
1922 formatteropts
1923 formatteropts
1923 + [
1924 + [
1924 (b'r', b'revs', [], b'restrict search to these revisions'),
1925 (b'r', b'revs', [], b'restrict search to these revisions'),
1925 (b'', b'timing', False, b'provides extra data (costly)'),
1926 (b'', b'timing', False, b'provides extra data (costly)'),
1926 (b'', b'stats', False, b'provides statistic about the measured data'),
1927 (b'', b'stats', False, b'provides statistic about the measured data'),
1927 ],
1928 ],
1928 )
1929 )
1929 def perfhelpermergecopies(ui, repo, revs=[], **opts):
1930 def perfhelpermergecopies(ui, repo, revs=[], **opts):
1930 """find statistics about potential parameters for `perfmergecopies`
1931 """find statistics about potential parameters for `perfmergecopies`
1931
1932
1932 This command find (base, p1, p2) triplet relevant for copytracing
1933 This command find (base, p1, p2) triplet relevant for copytracing
1933 benchmarking in the context of a merge. It reports values for some of the
1934 benchmarking in the context of a merge. It reports values for some of the
1934 parameters that impact merge copy tracing time during merge.
1935 parameters that impact merge copy tracing time during merge.
1935
1936
1936 If `--timing` is set, rename detection is run and the associated timing
1937 If `--timing` is set, rename detection is run and the associated timing
1937 will be reported. The extra details come at the cost of slower command
1938 will be reported. The extra details come at the cost of slower command
1938 execution.
1939 execution.
1939
1940
1940 Since rename detection is only run once, other factors might easily
1941 Since rename detection is only run once, other factors might easily
1941 affect the precision of the timing. However it should give a good
1942 affect the precision of the timing. However it should give a good
1942 approximation of which revision triplets are very costly.
1943 approximation of which revision triplets are very costly.
1943 """
1944 """
1944 opts = _byteskwargs(opts)
1945 opts = _byteskwargs(opts)
1945 fm = ui.formatter(b'perf', opts)
1946 fm = ui.formatter(b'perf', opts)
1946 dotiming = opts[b'timing']
1947 dotiming = opts[b'timing']
1947 dostats = opts[b'stats']
1948 dostats = opts[b'stats']
1948
1949
1949 output_template = [
1950 output_template = [
1950 ("base", "%(base)12s"),
1951 ("base", "%(base)12s"),
1951 ("p1", "%(p1.node)12s"),
1952 ("p1", "%(p1.node)12s"),
1952 ("p2", "%(p2.node)12s"),
1953 ("p2", "%(p2.node)12s"),
1953 ("p1.nb-revs", "%(p1.nbrevs)12d"),
1954 ("p1.nb-revs", "%(p1.nbrevs)12d"),
1954 ("p1.nb-files", "%(p1.nbmissingfiles)12d"),
1955 ("p1.nb-files", "%(p1.nbmissingfiles)12d"),
1955 ("p1.renames", "%(p1.renamedfiles)12d"),
1956 ("p1.renames", "%(p1.renamedfiles)12d"),
1956 ("p1.time", "%(p1.time)12.3f"),
1957 ("p1.time", "%(p1.time)12.3f"),
1957 ("p2.nb-revs", "%(p2.nbrevs)12d"),
1958 ("p2.nb-revs", "%(p2.nbrevs)12d"),
1958 ("p2.nb-files", "%(p2.nbmissingfiles)12d"),
1959 ("p2.nb-files", "%(p2.nbmissingfiles)12d"),
1959 ("p2.renames", "%(p2.renamedfiles)12d"),
1960 ("p2.renames", "%(p2.renamedfiles)12d"),
1960 ("p2.time", "%(p2.time)12.3f"),
1961 ("p2.time", "%(p2.time)12.3f"),
1961 ("renames", "%(nbrenamedfiles)12d"),
1962 ("renames", "%(nbrenamedfiles)12d"),
1962 ("total.time", "%(time)12.3f"),
1963 ("total.time", "%(time)12.3f"),
1963 ]
1964 ]
1964 if not dotiming:
1965 if not dotiming:
1965 output_template = [
1966 output_template = [
1966 i
1967 i
1967 for i in output_template
1968 for i in output_template
1968 if not ('time' in i[0] or 'renames' in i[0])
1969 if not ('time' in i[0] or 'renames' in i[0])
1969 ]
1970 ]
1970 header_names = [h for (h, v) in output_template]
1971 header_names = [h for (h, v) in output_template]
1971 output = ' '.join([v for (h, v) in output_template]) + '\n'
1972 output = ' '.join([v for (h, v) in output_template]) + '\n'
1972 header = ' '.join(['%12s'] * len(header_names)) + '\n'
1973 header = ' '.join(['%12s'] * len(header_names)) + '\n'
1973 fm.plain(header % tuple(header_names))
1974 fm.plain(header % tuple(header_names))
1974
1975
1975 if not revs:
1976 if not revs:
1976 revs = ['all()']
1977 revs = ['all()']
1977 revs = scmutil.revrange(repo, revs)
1978 revs = scmutil.revrange(repo, revs)
1978
1979
1979 if dostats:
1980 if dostats:
1980 alldata = {
1981 alldata = {
1981 'nbrevs': [],
1982 'nbrevs': [],
1982 'nbmissingfiles': [],
1983 'nbmissingfiles': [],
1983 }
1984 }
1984 if dotiming:
1985 if dotiming:
1985 alldata['parentnbrenames'] = []
1986 alldata['parentnbrenames'] = []
1986 alldata['totalnbrenames'] = []
1987 alldata['totalnbrenames'] = []
1987 alldata['parenttime'] = []
1988 alldata['parenttime'] = []
1988 alldata['totaltime'] = []
1989 alldata['totaltime'] = []
1989
1990
1990 roi = repo.revs('merge() and %ld', revs)
1991 roi = repo.revs('merge() and %ld', revs)
1991 for r in roi:
1992 for r in roi:
1992 ctx = repo[r]
1993 ctx = repo[r]
1993 p1 = ctx.p1()
1994 p1 = ctx.p1()
1994 p2 = ctx.p2()
1995 p2 = ctx.p2()
1995 bases = repo.changelog._commonancestorsheads(p1.rev(), p2.rev())
1996 bases = repo.changelog._commonancestorsheads(p1.rev(), p2.rev())
1996 for b in bases:
1997 for b in bases:
1997 b = repo[b]
1998 b = repo[b]
1998 p1missing = copies._computeforwardmissing(b, p1)
1999 p1missing = copies._computeforwardmissing(b, p1)
1999 p2missing = copies._computeforwardmissing(b, p2)
2000 p2missing = copies._computeforwardmissing(b, p2)
2000 data = {
2001 data = {
2001 b'base': b.hex(),
2002 b'base': b.hex(),
2002 b'p1.node': p1.hex(),
2003 b'p1.node': p1.hex(),
2003 b'p1.nbrevs': len(repo.revs('only(%d, %d)', p1.rev(), b.rev())),
2004 b'p1.nbrevs': len(repo.revs('only(%d, %d)', p1.rev(), b.rev())),
2004 b'p1.nbmissingfiles': len(p1missing),
2005 b'p1.nbmissingfiles': len(p1missing),
2005 b'p2.node': p2.hex(),
2006 b'p2.node': p2.hex(),
2006 b'p2.nbrevs': len(repo.revs('only(%d, %d)', p2.rev(), b.rev())),
2007 b'p2.nbrevs': len(repo.revs('only(%d, %d)', p2.rev(), b.rev())),
2007 b'p2.nbmissingfiles': len(p2missing),
2008 b'p2.nbmissingfiles': len(p2missing),
2008 }
2009 }
2009 if dostats:
2010 if dostats:
2010 if p1missing:
2011 if p1missing:
2011 alldata['nbrevs'].append(
2012 alldata['nbrevs'].append(
2012 (data['p1.nbrevs'], b.hex(), p1.hex())
2013 (data['p1.nbrevs'], b.hex(), p1.hex())
2013 )
2014 )
2014 alldata['nbmissingfiles'].append(
2015 alldata['nbmissingfiles'].append(
2015 (data['p1.nbmissingfiles'], b.hex(), p1.hex())
2016 (data['p1.nbmissingfiles'], b.hex(), p1.hex())
2016 )
2017 )
2017 if p2missing:
2018 if p2missing:
2018 alldata['nbrevs'].append(
2019 alldata['nbrevs'].append(
2019 (data['p2.nbrevs'], b.hex(), p2.hex())
2020 (data['p2.nbrevs'], b.hex(), p2.hex())
2020 )
2021 )
2021 alldata['nbmissingfiles'].append(
2022 alldata['nbmissingfiles'].append(
2022 (data['p2.nbmissingfiles'], b.hex(), p2.hex())
2023 (data['p2.nbmissingfiles'], b.hex(), p2.hex())
2023 )
2024 )
2024 if dotiming:
2025 if dotiming:
2025 begin = util.timer()
2026 begin = util.timer()
2026 mergedata = copies.mergecopies(repo, p1, p2, b)
2027 mergedata = copies.mergecopies(repo, p1, p2, b)
2027 end = util.timer()
2028 end = util.timer()
2028 # not very stable timing since we did only one run
2029 # not very stable timing since we did only one run
2029 data['time'] = end - begin
2030 data['time'] = end - begin
2030 # mergedata contains five dicts: "copy", "movewithdir",
2031 # mergedata contains five dicts: "copy", "movewithdir",
2031 # "diverge", "renamedelete" and "dirmove".
2032 # "diverge", "renamedelete" and "dirmove".
2032 # The first 4 are about renamed file so lets count that.
2033 # The first 4 are about renamed file so lets count that.
2033 renames = len(mergedata[0])
2034 renames = len(mergedata[0])
2034 renames += len(mergedata[1])
2035 renames += len(mergedata[1])
2035 renames += len(mergedata[2])
2036 renames += len(mergedata[2])
2036 renames += len(mergedata[3])
2037 renames += len(mergedata[3])
2037 data['nbrenamedfiles'] = renames
2038 data['nbrenamedfiles'] = renames
2038 begin = util.timer()
2039 begin = util.timer()
2039 p1renames = copies.pathcopies(b, p1)
2040 p1renames = copies.pathcopies(b, p1)
2040 end = util.timer()
2041 end = util.timer()
2041 data['p1.time'] = end - begin
2042 data['p1.time'] = end - begin
2042 begin = util.timer()
2043 begin = util.timer()
2043 p2renames = copies.pathcopies(b, p2)
2044 p2renames = copies.pathcopies(b, p2)
2044 data['p2.time'] = end - begin
2045 data['p2.time'] = end - begin
2045 end = util.timer()
2046 end = util.timer()
2046 data['p1.renamedfiles'] = len(p1renames)
2047 data['p1.renamedfiles'] = len(p1renames)
2047 data['p2.renamedfiles'] = len(p2renames)
2048 data['p2.renamedfiles'] = len(p2renames)
2048
2049
2049 if dostats:
2050 if dostats:
2050 if p1missing:
2051 if p1missing:
2051 alldata['parentnbrenames'].append(
2052 alldata['parentnbrenames'].append(
2052 (data['p1.renamedfiles'], b.hex(), p1.hex())
2053 (data['p1.renamedfiles'], b.hex(), p1.hex())
2053 )
2054 )
2054 alldata['parenttime'].append(
2055 alldata['parenttime'].append(
2055 (data['p1.time'], b.hex(), p1.hex())
2056 (data['p1.time'], b.hex(), p1.hex())
2056 )
2057 )
2057 if p2missing:
2058 if p2missing:
2058 alldata['parentnbrenames'].append(
2059 alldata['parentnbrenames'].append(
2059 (data['p2.renamedfiles'], b.hex(), p2.hex())
2060 (data['p2.renamedfiles'], b.hex(), p2.hex())
2060 )
2061 )
2061 alldata['parenttime'].append(
2062 alldata['parenttime'].append(
2062 (data['p2.time'], b.hex(), p2.hex())
2063 (data['p2.time'], b.hex(), p2.hex())
2063 )
2064 )
2064 if p1missing or p2missing:
2065 if p1missing or p2missing:
2065 alldata['totalnbrenames'].append(
2066 alldata['totalnbrenames'].append(
2066 (
2067 (
2067 data['nbrenamedfiles'],
2068 data['nbrenamedfiles'],
2068 b.hex(),
2069 b.hex(),
2069 p1.hex(),
2070 p1.hex(),
2070 p2.hex(),
2071 p2.hex(),
2071 )
2072 )
2072 )
2073 )
2073 alldata['totaltime'].append(
2074 alldata['totaltime'].append(
2074 (data['time'], b.hex(), p1.hex(), p2.hex())
2075 (data['time'], b.hex(), p1.hex(), p2.hex())
2075 )
2076 )
2076 fm.startitem()
2077 fm.startitem()
2077 fm.data(**data)
2078 fm.data(**data)
2078 # make node pretty for the human output
2079 # make node pretty for the human output
2079 out = data.copy()
2080 out = data.copy()
2080 out['base'] = fm.hexfunc(b.node())
2081 out['base'] = fm.hexfunc(b.node())
2081 out['p1.node'] = fm.hexfunc(p1.node())
2082 out['p1.node'] = fm.hexfunc(p1.node())
2082 out['p2.node'] = fm.hexfunc(p2.node())
2083 out['p2.node'] = fm.hexfunc(p2.node())
2083 fm.plain(output % out)
2084 fm.plain(output % out)
2084
2085
2085 fm.end()
2086 fm.end()
2086 if dostats:
2087 if dostats:
2087 # use a second formatter because the data are quite different, not sure
2088 # use a second formatter because the data are quite different, not sure
2088 # how it flies with the templater.
2089 # how it flies with the templater.
2089 entries = [
2090 entries = [
2090 ('nbrevs', 'number of revision covered'),
2091 ('nbrevs', 'number of revision covered'),
2091 ('nbmissingfiles', 'number of missing files at head'),
2092 ('nbmissingfiles', 'number of missing files at head'),
2092 ]
2093 ]
2093 if dotiming:
2094 if dotiming:
2094 entries.append(
2095 entries.append(
2095 ('parentnbrenames', 'rename from one parent to base')
2096 ('parentnbrenames', 'rename from one parent to base')
2096 )
2097 )
2097 entries.append(('totalnbrenames', 'total number of renames'))
2098 entries.append(('totalnbrenames', 'total number of renames'))
2098 entries.append(('parenttime', 'time for one parent'))
2099 entries.append(('parenttime', 'time for one parent'))
2099 entries.append(('totaltime', 'time for both parents'))
2100 entries.append(('totaltime', 'time for both parents'))
2100 _displaystats(ui, opts, entries, alldata)
2101 _displaystats(ui, opts, entries, alldata)
2101
2102
2102
2103
2103 @command(
2104 @command(
2104 b'perfhelper-pathcopies',
2105 b'perfhelper-pathcopies',
2105 formatteropts
2106 formatteropts
2106 + [
2107 + [
2107 (b'r', b'revs', [], b'restrict search to these revisions'),
2108 (b'r', b'revs', [], b'restrict search to these revisions'),
2108 (b'', b'timing', False, b'provides extra data (costly)'),
2109 (b'', b'timing', False, b'provides extra data (costly)'),
2109 (b'', b'stats', False, b'provides statistic about the measured data'),
2110 (b'', b'stats', False, b'provides statistic about the measured data'),
2110 ],
2111 ],
2111 )
2112 )
2112 def perfhelperpathcopies(ui, repo, revs=[], **opts):
2113 def perfhelperpathcopies(ui, repo, revs=[], **opts):
2113 """find statistic about potential parameters for the `perftracecopies`
2114 """find statistic about potential parameters for the `perftracecopies`
2114
2115
2115 This command find source-destination pair relevant for copytracing testing.
2116 This command find source-destination pair relevant for copytracing testing.
2116 It report value for some of the parameters that impact copy tracing time.
2117 It report value for some of the parameters that impact copy tracing time.
2117
2118
2118 If `--timing` is set, rename detection is run and the associated timing
2119 If `--timing` is set, rename detection is run and the associated timing
2119 will be reported. The extra details comes at the cost of a slower command
2120 will be reported. The extra details comes at the cost of a slower command
2120 execution.
2121 execution.
2121
2122
2122 Since the rename detection is only run once, other factors might easily
2123 Since the rename detection is only run once, other factors might easily
2123 affect the precision of the timing. However it should give a good
2124 affect the precision of the timing. However it should give a good
2124 approximation of which revision pairs are very costly.
2125 approximation of which revision pairs are very costly.
2125 """
2126 """
2126 opts = _byteskwargs(opts)
2127 opts = _byteskwargs(opts)
2127 fm = ui.formatter(b'perf', opts)
2128 fm = ui.formatter(b'perf', opts)
2128 dotiming = opts[b'timing']
2129 dotiming = opts[b'timing']
2129 dostats = opts[b'stats']
2130 dostats = opts[b'stats']
2130
2131
2131 if dotiming:
2132 if dotiming:
2132 header = '%12s %12s %12s %12s %12s %12s\n'
2133 header = '%12s %12s %12s %12s %12s %12s\n'
2133 output = (
2134 output = (
2134 "%(source)12s %(destination)12s "
2135 "%(source)12s %(destination)12s "
2135 "%(nbrevs)12d %(nbmissingfiles)12d "
2136 "%(nbrevs)12d %(nbmissingfiles)12d "
2136 "%(nbrenamedfiles)12d %(time)18.5f\n"
2137 "%(nbrenamedfiles)12d %(time)18.5f\n"
2137 )
2138 )
2138 header_names = (
2139 header_names = (
2139 "source",
2140 "source",
2140 "destination",
2141 "destination",
2141 "nb-revs",
2142 "nb-revs",
2142 "nb-files",
2143 "nb-files",
2143 "nb-renames",
2144 "nb-renames",
2144 "time",
2145 "time",
2145 )
2146 )
2146 fm.plain(header % header_names)
2147 fm.plain(header % header_names)
2147 else:
2148 else:
2148 header = '%12s %12s %12s %12s\n'
2149 header = '%12s %12s %12s %12s\n'
2149 output = (
2150 output = (
2150 "%(source)12s %(destination)12s "
2151 "%(source)12s %(destination)12s "
2151 "%(nbrevs)12d %(nbmissingfiles)12d\n"
2152 "%(nbrevs)12d %(nbmissingfiles)12d\n"
2152 )
2153 )
2153 fm.plain(header % ("source", "destination", "nb-revs", "nb-files"))
2154 fm.plain(header % ("source", "destination", "nb-revs", "nb-files"))
2154
2155
2155 if not revs:
2156 if not revs:
2156 revs = ['all()']
2157 revs = ['all()']
2157 revs = scmutil.revrange(repo, revs)
2158 revs = scmutil.revrange(repo, revs)
2158
2159
2159 if dostats:
2160 if dostats:
2160 alldata = {
2161 alldata = {
2161 'nbrevs': [],
2162 'nbrevs': [],
2162 'nbmissingfiles': [],
2163 'nbmissingfiles': [],
2163 }
2164 }
2164 if dotiming:
2165 if dotiming:
2165 alldata['nbrenames'] = []
2166 alldata['nbrenames'] = []
2166 alldata['time'] = []
2167 alldata['time'] = []
2167
2168
2168 roi = repo.revs('merge() and %ld', revs)
2169 roi = repo.revs('merge() and %ld', revs)
2169 for r in roi:
2170 for r in roi:
2170 ctx = repo[r]
2171 ctx = repo[r]
2171 p1 = ctx.p1().rev()
2172 p1 = ctx.p1().rev()
2172 p2 = ctx.p2().rev()
2173 p2 = ctx.p2().rev()
2173 bases = repo.changelog._commonancestorsheads(p1, p2)
2174 bases = repo.changelog._commonancestorsheads(p1, p2)
2174 for p in (p1, p2):
2175 for p in (p1, p2):
2175 for b in bases:
2176 for b in bases:
2176 base = repo[b]
2177 base = repo[b]
2177 parent = repo[p]
2178 parent = repo[p]
2178 missing = copies._computeforwardmissing(base, parent)
2179 missing = copies._computeforwardmissing(base, parent)
2179 if not missing:
2180 if not missing:
2180 continue
2181 continue
2181 data = {
2182 data = {
2182 b'source': base.hex(),
2183 b'source': base.hex(),
2183 b'destination': parent.hex(),
2184 b'destination': parent.hex(),
2184 b'nbrevs': len(repo.revs('only(%d, %d)', p, b)),
2185 b'nbrevs': len(repo.revs('only(%d, %d)', p, b)),
2185 b'nbmissingfiles': len(missing),
2186 b'nbmissingfiles': len(missing),
2186 }
2187 }
2187 if dostats:
2188 if dostats:
2188 alldata['nbrevs'].append(
2189 alldata['nbrevs'].append(
2189 (data['nbrevs'], base.hex(), parent.hex(),)
2190 (data['nbrevs'], base.hex(), parent.hex(),)
2190 )
2191 )
2191 alldata['nbmissingfiles'].append(
2192 alldata['nbmissingfiles'].append(
2192 (data['nbmissingfiles'], base.hex(), parent.hex(),)
2193 (data['nbmissingfiles'], base.hex(), parent.hex(),)
2193 )
2194 )
2194 if dotiming:
2195 if dotiming:
2195 begin = util.timer()
2196 begin = util.timer()
2196 renames = copies.pathcopies(base, parent)
2197 renames = copies.pathcopies(base, parent)
2197 end = util.timer()
2198 end = util.timer()
2198 # not very stable timing since we did only one run
2199 # not very stable timing since we did only one run
2199 data['time'] = end - begin
2200 data['time'] = end - begin
2200 data['nbrenamedfiles'] = len(renames)
2201 data['nbrenamedfiles'] = len(renames)
2201 if dostats:
2202 if dostats:
2202 alldata['time'].append(
2203 alldata['time'].append(
2203 (data['time'], base.hex(), parent.hex(),)
2204 (data['time'], base.hex(), parent.hex(),)
2204 )
2205 )
2205 alldata['nbrenames'].append(
2206 alldata['nbrenames'].append(
2206 (data['nbrenamedfiles'], base.hex(), parent.hex(),)
2207 (data['nbrenamedfiles'], base.hex(), parent.hex(),)
2207 )
2208 )
2208 fm.startitem()
2209 fm.startitem()
2209 fm.data(**data)
2210 fm.data(**data)
2210 out = data.copy()
2211 out = data.copy()
2211 out['source'] = fm.hexfunc(base.node())
2212 out['source'] = fm.hexfunc(base.node())
2212 out['destination'] = fm.hexfunc(parent.node())
2213 out['destination'] = fm.hexfunc(parent.node())
2213 fm.plain(output % out)
2214 fm.plain(output % out)
2214
2215
2215 fm.end()
2216 fm.end()
2216 if dostats:
2217 if dostats:
2217 # use a second formatter because the data are quite different, not sure
2218 # use a second formatter because the data are quite different, not sure
2218 # how it flies with the templater.
2219 # how it flies with the templater.
2219 fm = ui.formatter(b'perf', opts)
2220 fm = ui.formatter(b'perf', opts)
2220 entries = [
2221 entries = [
2221 ('nbrevs', 'number of revision covered'),
2222 ('nbrevs', 'number of revision covered'),
2222 ('nbmissingfiles', 'number of missing files at head'),
2223 ('nbmissingfiles', 'number of missing files at head'),
2223 ]
2224 ]
2224 if dotiming:
2225 if dotiming:
2225 entries.append(('nbrenames', 'renamed files'))
2226 entries.append(('nbrenames', 'renamed files'))
2226 entries.append(('time', 'time'))
2227 entries.append(('time', 'time'))
2227 _displaystats(ui, opts, entries, alldata)
2228 _displaystats(ui, opts, entries, alldata)
2228
2229
2229
2230
2230 @command(b'perfcca', formatteropts)
2231 @command(b'perfcca', formatteropts)
2231 def perfcca(ui, repo, **opts):
2232 def perfcca(ui, repo, **opts):
2232 opts = _byteskwargs(opts)
2233 opts = _byteskwargs(opts)
2233 timer, fm = gettimer(ui, opts)
2234 timer, fm = gettimer(ui, opts)
2234 timer(lambda: scmutil.casecollisionauditor(ui, False, repo.dirstate))
2235 timer(lambda: scmutil.casecollisionauditor(ui, False, repo.dirstate))
2235 fm.end()
2236 fm.end()
2236
2237
2237
2238
2238 @command(b'perffncacheload', formatteropts)
2239 @command(b'perffncacheload', formatteropts)
2239 def perffncacheload(ui, repo, **opts):
2240 def perffncacheload(ui, repo, **opts):
2240 opts = _byteskwargs(opts)
2241 opts = _byteskwargs(opts)
2241 timer, fm = gettimer(ui, opts)
2242 timer, fm = gettimer(ui, opts)
2242 s = repo.store
2243 s = repo.store
2243
2244
2244 def d():
2245 def d():
2245 s.fncache._load()
2246 s.fncache._load()
2246
2247
2247 timer(d)
2248 timer(d)
2248 fm.end()
2249 fm.end()
2249
2250
2250
2251
2251 @command(b'perffncachewrite', formatteropts)
2252 @command(b'perffncachewrite', formatteropts)
2252 def perffncachewrite(ui, repo, **opts):
2253 def perffncachewrite(ui, repo, **opts):
2253 opts = _byteskwargs(opts)
2254 opts = _byteskwargs(opts)
2254 timer, fm = gettimer(ui, opts)
2255 timer, fm = gettimer(ui, opts)
2255 s = repo.store
2256 s = repo.store
2256 lock = repo.lock()
2257 lock = repo.lock()
2257 s.fncache._load()
2258 s.fncache._load()
2258 tr = repo.transaction(b'perffncachewrite')
2259 tr = repo.transaction(b'perffncachewrite')
2259 tr.addbackup(b'fncache')
2260 tr.addbackup(b'fncache')
2260
2261
2261 def d():
2262 def d():
2262 s.fncache._dirty = True
2263 s.fncache._dirty = True
2263 s.fncache.write(tr)
2264 s.fncache.write(tr)
2264
2265
2265 timer(d)
2266 timer(d)
2266 tr.close()
2267 tr.close()
2267 lock.release()
2268 lock.release()
2268 fm.end()
2269 fm.end()
2269
2270
2270
2271
2271 @command(b'perffncacheencode', formatteropts)
2272 @command(b'perffncacheencode', formatteropts)
2272 def perffncacheencode(ui, repo, **opts):
2273 def perffncacheencode(ui, repo, **opts):
2273 opts = _byteskwargs(opts)
2274 opts = _byteskwargs(opts)
2274 timer, fm = gettimer(ui, opts)
2275 timer, fm = gettimer(ui, opts)
2275 s = repo.store
2276 s = repo.store
2276 s.fncache._load()
2277 s.fncache._load()
2277
2278
2278 def d():
2279 def d():
2279 for p in s.fncache.entries:
2280 for p in s.fncache.entries:
2280 s.encode(p)
2281 s.encode(p)
2281
2282
2282 timer(d)
2283 timer(d)
2283 fm.end()
2284 fm.end()
2284
2285
2285
2286
2286 def _bdiffworker(q, blocks, xdiff, ready, done):
2287 def _bdiffworker(q, blocks, xdiff, ready, done):
2287 while not done.is_set():
2288 while not done.is_set():
2288 pair = q.get()
2289 pair = q.get()
2289 while pair is not None:
2290 while pair is not None:
2290 if xdiff:
2291 if xdiff:
2291 mdiff.bdiff.xdiffblocks(*pair)
2292 mdiff.bdiff.xdiffblocks(*pair)
2292 elif blocks:
2293 elif blocks:
2293 mdiff.bdiff.blocks(*pair)
2294 mdiff.bdiff.blocks(*pair)
2294 else:
2295 else:
2295 mdiff.textdiff(*pair)
2296 mdiff.textdiff(*pair)
2296 q.task_done()
2297 q.task_done()
2297 pair = q.get()
2298 pair = q.get()
2298 q.task_done() # for the None one
2299 q.task_done() # for the None one
2299 with ready:
2300 with ready:
2300 ready.wait()
2301 ready.wait()
2301
2302
2302
2303
2303 def _manifestrevision(repo, mnode):
2304 def _manifestrevision(repo, mnode):
2304 ml = repo.manifestlog
2305 ml = repo.manifestlog
2305
2306
2306 if util.safehasattr(ml, b'getstorage'):
2307 if util.safehasattr(ml, b'getstorage'):
2307 store = ml.getstorage(b'')
2308 store = ml.getstorage(b'')
2308 else:
2309 else:
2309 store = ml._revlog
2310 store = ml._revlog
2310
2311
2311 return store.revision(mnode)
2312 return store.revision(mnode)
2312
2313
2313
2314
2314 @command(
2315 @command(
2315 b'perfbdiff',
2316 b'perfbdiff',
2316 revlogopts
2317 revlogopts
2317 + formatteropts
2318 + formatteropts
2318 + [
2319 + [
2319 (
2320 (
2320 b'',
2321 b'',
2321 b'count',
2322 b'count',
2322 1,
2323 1,
2323 b'number of revisions to test (when using --startrev)',
2324 b'number of revisions to test (when using --startrev)',
2324 ),
2325 ),
2325 (b'', b'alldata', False, b'test bdiffs for all associated revisions'),
2326 (b'', b'alldata', False, b'test bdiffs for all associated revisions'),
2326 (b'', b'threads', 0, b'number of thread to use (disable with 0)'),
2327 (b'', b'threads', 0, b'number of thread to use (disable with 0)'),
2327 (b'', b'blocks', False, b'test computing diffs into blocks'),
2328 (b'', b'blocks', False, b'test computing diffs into blocks'),
2328 (b'', b'xdiff', False, b'use xdiff algorithm'),
2329 (b'', b'xdiff', False, b'use xdiff algorithm'),
2329 ],
2330 ],
2330 b'-c|-m|FILE REV',
2331 b'-c|-m|FILE REV',
2331 )
2332 )
2332 def perfbdiff(ui, repo, file_, rev=None, count=None, threads=0, **opts):
2333 def perfbdiff(ui, repo, file_, rev=None, count=None, threads=0, **opts):
2333 """benchmark a bdiff between revisions
2334 """benchmark a bdiff between revisions
2334
2335
2335 By default, benchmark a bdiff between its delta parent and itself.
2336 By default, benchmark a bdiff between its delta parent and itself.
2336
2337
2337 With ``--count``, benchmark bdiffs between delta parents and self for N
2338 With ``--count``, benchmark bdiffs between delta parents and self for N
2338 revisions starting at the specified revision.
2339 revisions starting at the specified revision.
2339
2340
2340 With ``--alldata``, assume the requested revision is a changeset and
2341 With ``--alldata``, assume the requested revision is a changeset and
2341 measure bdiffs for all changes related to that changeset (manifest
2342 measure bdiffs for all changes related to that changeset (manifest
2342 and filelogs).
2343 and filelogs).
2343 """
2344 """
2344 opts = _byteskwargs(opts)
2345 opts = _byteskwargs(opts)
2345
2346
2346 if opts[b'xdiff'] and not opts[b'blocks']:
2347 if opts[b'xdiff'] and not opts[b'blocks']:
2347 raise error.CommandError(b'perfbdiff', b'--xdiff requires --blocks')
2348 raise error.CommandError(b'perfbdiff', b'--xdiff requires --blocks')
2348
2349
2349 if opts[b'alldata']:
2350 if opts[b'alldata']:
2350 opts[b'changelog'] = True
2351 opts[b'changelog'] = True
2351
2352
2352 if opts.get(b'changelog') or opts.get(b'manifest'):
2353 if opts.get(b'changelog') or opts.get(b'manifest'):
2353 file_, rev = None, file_
2354 file_, rev = None, file_
2354 elif rev is None:
2355 elif rev is None:
2355 raise error.CommandError(b'perfbdiff', b'invalid arguments')
2356 raise error.CommandError(b'perfbdiff', b'invalid arguments')
2356
2357
2357 blocks = opts[b'blocks']
2358 blocks = opts[b'blocks']
2358 xdiff = opts[b'xdiff']
2359 xdiff = opts[b'xdiff']
2359 textpairs = []
2360 textpairs = []
2360
2361
2361 r = cmdutil.openrevlog(repo, b'perfbdiff', file_, opts)
2362 r = cmdutil.openrevlog(repo, b'perfbdiff', file_, opts)
2362
2363
2363 startrev = r.rev(r.lookup(rev))
2364 startrev = r.rev(r.lookup(rev))
2364 for rev in range(startrev, min(startrev + count, len(r) - 1)):
2365 for rev in range(startrev, min(startrev + count, len(r) - 1)):
2365 if opts[b'alldata']:
2366 if opts[b'alldata']:
2366 # Load revisions associated with changeset.
2367 # Load revisions associated with changeset.
2367 ctx = repo[rev]
2368 ctx = repo[rev]
2368 mtext = _manifestrevision(repo, ctx.manifestnode())
2369 mtext = _manifestrevision(repo, ctx.manifestnode())
2369 for pctx in ctx.parents():
2370 for pctx in ctx.parents():
2370 pman = _manifestrevision(repo, pctx.manifestnode())
2371 pman = _manifestrevision(repo, pctx.manifestnode())
2371 textpairs.append((pman, mtext))
2372 textpairs.append((pman, mtext))
2372
2373
2373 # Load filelog revisions by iterating manifest delta.
2374 # Load filelog revisions by iterating manifest delta.
2374 man = ctx.manifest()
2375 man = ctx.manifest()
2375 pman = ctx.p1().manifest()
2376 pman = ctx.p1().manifest()
2376 for filename, change in pman.diff(man).items():
2377 for filename, change in pman.diff(man).items():
2377 fctx = repo.file(filename)
2378 fctx = repo.file(filename)
2378 f1 = fctx.revision(change[0][0] or -1)
2379 f1 = fctx.revision(change[0][0] or -1)
2379 f2 = fctx.revision(change[1][0] or -1)
2380 f2 = fctx.revision(change[1][0] or -1)
2380 textpairs.append((f1, f2))
2381 textpairs.append((f1, f2))
2381 else:
2382 else:
2382 dp = r.deltaparent(rev)
2383 dp = r.deltaparent(rev)
2383 textpairs.append((r.revision(dp), r.revision(rev)))
2384 textpairs.append((r.revision(dp), r.revision(rev)))
2384
2385
2385 withthreads = threads > 0
2386 withthreads = threads > 0
2386 if not withthreads:
2387 if not withthreads:
2387
2388
2388 def d():
2389 def d():
2389 for pair in textpairs:
2390 for pair in textpairs:
2390 if xdiff:
2391 if xdiff:
2391 mdiff.bdiff.xdiffblocks(*pair)
2392 mdiff.bdiff.xdiffblocks(*pair)
2392 elif blocks:
2393 elif blocks:
2393 mdiff.bdiff.blocks(*pair)
2394 mdiff.bdiff.blocks(*pair)
2394 else:
2395 else:
2395 mdiff.textdiff(*pair)
2396 mdiff.textdiff(*pair)
2396
2397
2397 else:
2398 else:
2398 q = queue()
2399 q = queue()
2399 for i in _xrange(threads):
2400 for i in _xrange(threads):
2400 q.put(None)
2401 q.put(None)
2401 ready = threading.Condition()
2402 ready = threading.Condition()
2402 done = threading.Event()
2403 done = threading.Event()
2403 for i in _xrange(threads):
2404 for i in _xrange(threads):
2404 threading.Thread(
2405 threading.Thread(
2405 target=_bdiffworker, args=(q, blocks, xdiff, ready, done)
2406 target=_bdiffworker, args=(q, blocks, xdiff, ready, done)
2406 ).start()
2407 ).start()
2407 q.join()
2408 q.join()
2408
2409
2409 def d():
2410 def d():
2410 for pair in textpairs:
2411 for pair in textpairs:
2411 q.put(pair)
2412 q.put(pair)
2412 for i in _xrange(threads):
2413 for i in _xrange(threads):
2413 q.put(None)
2414 q.put(None)
2414 with ready:
2415 with ready:
2415 ready.notify_all()
2416 ready.notify_all()
2416 q.join()
2417 q.join()
2417
2418
2418 timer, fm = gettimer(ui, opts)
2419 timer, fm = gettimer(ui, opts)
2419 timer(d)
2420 timer(d)
2420 fm.end()
2421 fm.end()
2421
2422
2422 if withthreads:
2423 if withthreads:
2423 done.set()
2424 done.set()
2424 for i in _xrange(threads):
2425 for i in _xrange(threads):
2425 q.put(None)
2426 q.put(None)
2426 with ready:
2427 with ready:
2427 ready.notify_all()
2428 ready.notify_all()
2428
2429
2429
2430
2430 @command(
2431 @command(
2431 b'perfunidiff',
2432 b'perfunidiff',
2432 revlogopts
2433 revlogopts
2433 + formatteropts
2434 + formatteropts
2434 + [
2435 + [
2435 (
2436 (
2436 b'',
2437 b'',
2437 b'count',
2438 b'count',
2438 1,
2439 1,
2439 b'number of revisions to test (when using --startrev)',
2440 b'number of revisions to test (when using --startrev)',
2440 ),
2441 ),
2441 (b'', b'alldata', False, b'test unidiffs for all associated revisions'),
2442 (b'', b'alldata', False, b'test unidiffs for all associated revisions'),
2442 ],
2443 ],
2443 b'-c|-m|FILE REV',
2444 b'-c|-m|FILE REV',
2444 )
2445 )
2445 def perfunidiff(ui, repo, file_, rev=None, count=None, **opts):
2446 def perfunidiff(ui, repo, file_, rev=None, count=None, **opts):
2446 """benchmark a unified diff between revisions
2447 """benchmark a unified diff between revisions
2447
2448
2448 This doesn't include any copy tracing - it's just a unified diff
2449 This doesn't include any copy tracing - it's just a unified diff
2449 of the texts.
2450 of the texts.
2450
2451
2451 By default, benchmark a diff between its delta parent and itself.
2452 By default, benchmark a diff between its delta parent and itself.
2452
2453
2453 With ``--count``, benchmark diffs between delta parents and self for N
2454 With ``--count``, benchmark diffs between delta parents and self for N
2454 revisions starting at the specified revision.
2455 revisions starting at the specified revision.
2455
2456
2456 With ``--alldata``, assume the requested revision is a changeset and
2457 With ``--alldata``, assume the requested revision is a changeset and
2457 measure diffs for all changes related to that changeset (manifest
2458 measure diffs for all changes related to that changeset (manifest
2458 and filelogs).
2459 and filelogs).
2459 """
2460 """
2460 opts = _byteskwargs(opts)
2461 opts = _byteskwargs(opts)
2461 if opts[b'alldata']:
2462 if opts[b'alldata']:
2462 opts[b'changelog'] = True
2463 opts[b'changelog'] = True
2463
2464
2464 if opts.get(b'changelog') or opts.get(b'manifest'):
2465 if opts.get(b'changelog') or opts.get(b'manifest'):
2465 file_, rev = None, file_
2466 file_, rev = None, file_
2466 elif rev is None:
2467 elif rev is None:
2467 raise error.CommandError(b'perfunidiff', b'invalid arguments')
2468 raise error.CommandError(b'perfunidiff', b'invalid arguments')
2468
2469
2469 textpairs = []
2470 textpairs = []
2470
2471
2471 r = cmdutil.openrevlog(repo, b'perfunidiff', file_, opts)
2472 r = cmdutil.openrevlog(repo, b'perfunidiff', file_, opts)
2472
2473
2473 startrev = r.rev(r.lookup(rev))
2474 startrev = r.rev(r.lookup(rev))
2474 for rev in range(startrev, min(startrev + count, len(r) - 1)):
2475 for rev in range(startrev, min(startrev + count, len(r) - 1)):
2475 if opts[b'alldata']:
2476 if opts[b'alldata']:
2476 # Load revisions associated with changeset.
2477 # Load revisions associated with changeset.
2477 ctx = repo[rev]
2478 ctx = repo[rev]
2478 mtext = _manifestrevision(repo, ctx.manifestnode())
2479 mtext = _manifestrevision(repo, ctx.manifestnode())
2479 for pctx in ctx.parents():
2480 for pctx in ctx.parents():
2480 pman = _manifestrevision(repo, pctx.manifestnode())
2481 pman = _manifestrevision(repo, pctx.manifestnode())
2481 textpairs.append((pman, mtext))
2482 textpairs.append((pman, mtext))
2482
2483
2483 # Load filelog revisions by iterating manifest delta.
2484 # Load filelog revisions by iterating manifest delta.
2484 man = ctx.manifest()
2485 man = ctx.manifest()
2485 pman = ctx.p1().manifest()
2486 pman = ctx.p1().manifest()
2486 for filename, change in pman.diff(man).items():
2487 for filename, change in pman.diff(man).items():
2487 fctx = repo.file(filename)
2488 fctx = repo.file(filename)
2488 f1 = fctx.revision(change[0][0] or -1)
2489 f1 = fctx.revision(change[0][0] or -1)
2489 f2 = fctx.revision(change[1][0] or -1)
2490 f2 = fctx.revision(change[1][0] or -1)
2490 textpairs.append((f1, f2))
2491 textpairs.append((f1, f2))
2491 else:
2492 else:
2492 dp = r.deltaparent(rev)
2493 dp = r.deltaparent(rev)
2493 textpairs.append((r.revision(dp), r.revision(rev)))
2494 textpairs.append((r.revision(dp), r.revision(rev)))
2494
2495
2495 def d():
2496 def d():
2496 for left, right in textpairs:
2497 for left, right in textpairs:
2497 # The date strings don't matter, so we pass empty strings.
2498 # The date strings don't matter, so we pass empty strings.
2498 headerlines, hunks = mdiff.unidiff(
2499 headerlines, hunks = mdiff.unidiff(
2499 left, b'', right, b'', b'left', b'right', binary=False
2500 left, b'', right, b'', b'left', b'right', binary=False
2500 )
2501 )
2501 # consume iterators in roughly the way patch.py does
2502 # consume iterators in roughly the way patch.py does
2502 b'\n'.join(headerlines)
2503 b'\n'.join(headerlines)
2503 b''.join(sum((list(hlines) for hrange, hlines in hunks), []))
2504 b''.join(sum((list(hlines) for hrange, hlines in hunks), []))
2504
2505
2505 timer, fm = gettimer(ui, opts)
2506 timer, fm = gettimer(ui, opts)
2506 timer(d)
2507 timer(d)
2507 fm.end()
2508 fm.end()
2508
2509
2509
2510
2510 @command(b'perfdiffwd', formatteropts)
2511 @command(b'perfdiffwd', formatteropts)
2511 def perfdiffwd(ui, repo, **opts):
2512 def perfdiffwd(ui, repo, **opts):
2512 """Profile diff of working directory changes"""
2513 """Profile diff of working directory changes"""
2513 opts = _byteskwargs(opts)
2514 opts = _byteskwargs(opts)
2514 timer, fm = gettimer(ui, opts)
2515 timer, fm = gettimer(ui, opts)
2515 options = {
2516 options = {
2516 'w': 'ignore_all_space',
2517 'w': 'ignore_all_space',
2517 'b': 'ignore_space_change',
2518 'b': 'ignore_space_change',
2518 'B': 'ignore_blank_lines',
2519 'B': 'ignore_blank_lines',
2519 }
2520 }
2520
2521
2521 for diffopt in ('', 'w', 'b', 'B', 'wB'):
2522 for diffopt in ('', 'w', 'b', 'B', 'wB'):
2522 opts = dict((options[c], b'1') for c in diffopt)
2523 opts = dict((options[c], b'1') for c in diffopt)
2523
2524
2524 def d():
2525 def d():
2525 ui.pushbuffer()
2526 ui.pushbuffer()
2526 commands.diff(ui, repo, **opts)
2527 commands.diff(ui, repo, **opts)
2527 ui.popbuffer()
2528 ui.popbuffer()
2528
2529
2529 diffopt = diffopt.encode('ascii')
2530 diffopt = diffopt.encode('ascii')
2530 title = b'diffopts: %s' % (diffopt and (b'-' + diffopt) or b'none')
2531 title = b'diffopts: %s' % (diffopt and (b'-' + diffopt) or b'none')
2531 timer(d, title=title)
2532 timer(d, title=title)
2532 fm.end()
2533 fm.end()
2533
2534
2534
2535
2535 @command(b'perfrevlogindex', revlogopts + formatteropts, b'-c|-m|FILE')
2536 @command(b'perfrevlogindex', revlogopts + formatteropts, b'-c|-m|FILE')
2536 def perfrevlogindex(ui, repo, file_=None, **opts):
2537 def perfrevlogindex(ui, repo, file_=None, **opts):
2537 """Benchmark operations against a revlog index.
2538 """Benchmark operations against a revlog index.
2538
2539
2539 This tests constructing a revlog instance, reading index data,
2540 This tests constructing a revlog instance, reading index data,
2540 parsing index data, and performing various operations related to
2541 parsing index data, and performing various operations related to
2541 index data.
2542 index data.
2542 """
2543 """
2543
2544
2544 opts = _byteskwargs(opts)
2545 opts = _byteskwargs(opts)
2545
2546
2546 rl = cmdutil.openrevlog(repo, b'perfrevlogindex', file_, opts)
2547 rl = cmdutil.openrevlog(repo, b'perfrevlogindex', file_, opts)
2547
2548
2548 opener = getattr(rl, 'opener') # trick linter
2549 opener = getattr(rl, 'opener') # trick linter
2549 indexfile = rl.indexfile
2550 indexfile = rl.indexfile
2550 data = opener.read(indexfile)
2551 data = opener.read(indexfile)
2551
2552
2552 header = struct.unpack(b'>I', data[0:4])[0]
2553 header = struct.unpack(b'>I', data[0:4])[0]
2553 version = header & 0xFFFF
2554 version = header & 0xFFFF
2554 if version == 1:
2555 if version == 1:
2555 revlogio = revlog.revlogio()
2556 revlogio = revlog.revlogio()
2556 inline = header & (1 << 16)
2557 inline = header & (1 << 16)
2557 else:
2558 else:
2558 raise error.Abort(b'unsupported revlog version: %d' % version)
2559 raise error.Abort(b'unsupported revlog version: %d' % version)
2559
2560
2560 rllen = len(rl)
2561 rllen = len(rl)
2561
2562
2562 node0 = rl.node(0)
2563 node0 = rl.node(0)
2563 node25 = rl.node(rllen // 4)
2564 node25 = rl.node(rllen // 4)
2564 node50 = rl.node(rllen // 2)
2565 node50 = rl.node(rllen // 2)
2565 node75 = rl.node(rllen // 4 * 3)
2566 node75 = rl.node(rllen // 4 * 3)
2566 node100 = rl.node(rllen - 1)
2567 node100 = rl.node(rllen - 1)
2567
2568
2568 allrevs = range(rllen)
2569 allrevs = range(rllen)
2569 allrevsrev = list(reversed(allrevs))
2570 allrevsrev = list(reversed(allrevs))
2570 allnodes = [rl.node(rev) for rev in range(rllen)]
2571 allnodes = [rl.node(rev) for rev in range(rllen)]
2571 allnodesrev = list(reversed(allnodes))
2572 allnodesrev = list(reversed(allnodes))
2572
2573
2573 def constructor():
2574 def constructor():
2574 revlog.revlog(opener, indexfile)
2575 revlog.revlog(opener, indexfile)
2575
2576
2576 def read():
2577 def read():
2577 with opener(indexfile) as fh:
2578 with opener(indexfile) as fh:
2578 fh.read()
2579 fh.read()
2579
2580
2580 def parseindex():
2581 def parseindex():
2581 revlogio.parseindex(data, inline)
2582 revlogio.parseindex(data, inline)
2582
2583
2583 def getentry(revornode):
2584 def getentry(revornode):
2584 index = revlogio.parseindex(data, inline)[0]
2585 index = revlogio.parseindex(data, inline)[0]
2585 index[revornode]
2586 index[revornode]
2586
2587
2587 def getentries(revs, count=1):
2588 def getentries(revs, count=1):
2588 index = revlogio.parseindex(data, inline)[0]
2589 index = revlogio.parseindex(data, inline)[0]
2589
2590
2590 for i in range(count):
2591 for i in range(count):
2591 for rev in revs:
2592 for rev in revs:
2592 index[rev]
2593 index[rev]
2593
2594
2594 def resolvenode(node):
2595 def resolvenode(node):
2595 nodemap = getattr(revlogio.parseindex(data, inline)[0], 'nodemap', None)
2596 nodemap = getattr(revlogio.parseindex(data, inline)[0], 'nodemap', None)
2596 # This only works for the C code.
2597 # This only works for the C code.
2597 if nodemap is None:
2598 if nodemap is None:
2598 return
2599 return
2599
2600
2600 try:
2601 try:
2601 nodemap[node]
2602 nodemap[node]
2602 except error.RevlogError:
2603 except error.RevlogError:
2603 pass
2604 pass
2604
2605
2605 def resolvenodes(nodes, count=1):
2606 def resolvenodes(nodes, count=1):
2606 nodemap = getattr(revlogio.parseindex(data, inline)[0], 'nodemap', None)
2607 nodemap = getattr(revlogio.parseindex(data, inline)[0], 'nodemap', None)
2607 if nodemap is None:
2608 if nodemap is None:
2608 return
2609 return
2609
2610
2610 for i in range(count):
2611 for i in range(count):
2611 for node in nodes:
2612 for node in nodes:
2612 try:
2613 try:
2613 nodemap[node]
2614 nodemap[node]
2614 except error.RevlogError:
2615 except error.RevlogError:
2615 pass
2616 pass
2616
2617
2617 benches = [
2618 benches = [
2618 (constructor, b'revlog constructor'),
2619 (constructor, b'revlog constructor'),
2619 (read, b'read'),
2620 (read, b'read'),
2620 (parseindex, b'create index object'),
2621 (parseindex, b'create index object'),
2621 (lambda: getentry(0), b'retrieve index entry for rev 0'),
2622 (lambda: getentry(0), b'retrieve index entry for rev 0'),
2622 (lambda: resolvenode(b'a' * 20), b'look up missing node'),
2623 (lambda: resolvenode(b'a' * 20), b'look up missing node'),
2623 (lambda: resolvenode(node0), b'look up node at rev 0'),
2624 (lambda: resolvenode(node0), b'look up node at rev 0'),
2624 (lambda: resolvenode(node25), b'look up node at 1/4 len'),
2625 (lambda: resolvenode(node25), b'look up node at 1/4 len'),
2625 (lambda: resolvenode(node50), b'look up node at 1/2 len'),
2626 (lambda: resolvenode(node50), b'look up node at 1/2 len'),
2626 (lambda: resolvenode(node75), b'look up node at 3/4 len'),
2627 (lambda: resolvenode(node75), b'look up node at 3/4 len'),
2627 (lambda: resolvenode(node100), b'look up node at tip'),
2628 (lambda: resolvenode(node100), b'look up node at tip'),
2628 # 2x variation is to measure caching impact.
2629 # 2x variation is to measure caching impact.
2629 (lambda: resolvenodes(allnodes), b'look up all nodes (forward)'),
2630 (lambda: resolvenodes(allnodes), b'look up all nodes (forward)'),
2630 (lambda: resolvenodes(allnodes, 2), b'look up all nodes 2x (forward)'),
2631 (lambda: resolvenodes(allnodes, 2), b'look up all nodes 2x (forward)'),
2631 (lambda: resolvenodes(allnodesrev), b'look up all nodes (reverse)'),
2632 (lambda: resolvenodes(allnodesrev), b'look up all nodes (reverse)'),
2632 (
2633 (
2633 lambda: resolvenodes(allnodesrev, 2),
2634 lambda: resolvenodes(allnodesrev, 2),
2634 b'look up all nodes 2x (reverse)',
2635 b'look up all nodes 2x (reverse)',
2635 ),
2636 ),
2636 (lambda: getentries(allrevs), b'retrieve all index entries (forward)'),
2637 (lambda: getentries(allrevs), b'retrieve all index entries (forward)'),
2637 (
2638 (
2638 lambda: getentries(allrevs, 2),
2639 lambda: getentries(allrevs, 2),
2639 b'retrieve all index entries 2x (forward)',
2640 b'retrieve all index entries 2x (forward)',
2640 ),
2641 ),
2641 (
2642 (
2642 lambda: getentries(allrevsrev),
2643 lambda: getentries(allrevsrev),
2643 b'retrieve all index entries (reverse)',
2644 b'retrieve all index entries (reverse)',
2644 ),
2645 ),
2645 (
2646 (
2646 lambda: getentries(allrevsrev, 2),
2647 lambda: getentries(allrevsrev, 2),
2647 b'retrieve all index entries 2x (reverse)',
2648 b'retrieve all index entries 2x (reverse)',
2648 ),
2649 ),
2649 ]
2650 ]
2650
2651
2651 for fn, title in benches:
2652 for fn, title in benches:
2652 timer, fm = gettimer(ui, opts)
2653 timer, fm = gettimer(ui, opts)
2653 timer(fn, title=title)
2654 timer(fn, title=title)
2654 fm.end()
2655 fm.end()
2655
2656
2656
2657
2657 @command(
2658 @command(
2658 b'perfrevlogrevisions',
2659 b'perfrevlogrevisions',
2659 revlogopts
2660 revlogopts
2660 + formatteropts
2661 + formatteropts
2661 + [
2662 + [
2662 (b'd', b'dist', 100, b'distance between the revisions'),
2663 (b'd', b'dist', 100, b'distance between the revisions'),
2663 (b's', b'startrev', 0, b'revision to start reading at'),
2664 (b's', b'startrev', 0, b'revision to start reading at'),
2664 (b'', b'reverse', False, b'read in reverse'),
2665 (b'', b'reverse', False, b'read in reverse'),
2665 ],
2666 ],
2666 b'-c|-m|FILE',
2667 b'-c|-m|FILE',
2667 )
2668 )
2668 def perfrevlogrevisions(
2669 def perfrevlogrevisions(
2669 ui, repo, file_=None, startrev=0, reverse=False, **opts
2670 ui, repo, file_=None, startrev=0, reverse=False, **opts
2670 ):
2671 ):
2671 """Benchmark reading a series of revisions from a revlog.
2672 """Benchmark reading a series of revisions from a revlog.
2672
2673
2673 By default, we read every ``-d/--dist`` revision from 0 to tip of
2674 By default, we read every ``-d/--dist`` revision from 0 to tip of
2674 the specified revlog.
2675 the specified revlog.
2675
2676
2676 The start revision can be defined via ``-s/--startrev``.
2677 The start revision can be defined via ``-s/--startrev``.
2677 """
2678 """
2678 opts = _byteskwargs(opts)
2679 opts = _byteskwargs(opts)
2679
2680
2680 rl = cmdutil.openrevlog(repo, b'perfrevlogrevisions', file_, opts)
2681 rl = cmdutil.openrevlog(repo, b'perfrevlogrevisions', file_, opts)
2681 rllen = getlen(ui)(rl)
2682 rllen = getlen(ui)(rl)
2682
2683
2683 if startrev < 0:
2684 if startrev < 0:
2684 startrev = rllen + startrev
2685 startrev = rllen + startrev
2685
2686
2686 def d():
2687 def d():
2687 rl.clearcaches()
2688 rl.clearcaches()
2688
2689
2689 beginrev = startrev
2690 beginrev = startrev
2690 endrev = rllen
2691 endrev = rllen
2691 dist = opts[b'dist']
2692 dist = opts[b'dist']
2692
2693
2693 if reverse:
2694 if reverse:
2694 beginrev, endrev = endrev - 1, beginrev - 1
2695 beginrev, endrev = endrev - 1, beginrev - 1
2695 dist = -1 * dist
2696 dist = -1 * dist
2696
2697
2697 for x in _xrange(beginrev, endrev, dist):
2698 for x in _xrange(beginrev, endrev, dist):
2698 # Old revisions don't support passing int.
2699 # Old revisions don't support passing int.
2699 n = rl.node(x)
2700 n = rl.node(x)
2700 rl.revision(n)
2701 rl.revision(n)
2701
2702
2702 timer, fm = gettimer(ui, opts)
2703 timer, fm = gettimer(ui, opts)
2703 timer(d)
2704 timer(d)
2704 fm.end()
2705 fm.end()
2705
2706
2706
2707
2707 @command(
2708 @command(
2708 b'perfrevlogwrite',
2709 b'perfrevlogwrite',
2709 revlogopts
2710 revlogopts
2710 + formatteropts
2711 + formatteropts
2711 + [
2712 + [
2712 (b's', b'startrev', 1000, b'revision to start writing at'),
2713 (b's', b'startrev', 1000, b'revision to start writing at'),
2713 (b'', b'stoprev', -1, b'last revision to write'),
2714 (b'', b'stoprev', -1, b'last revision to write'),
2714 (b'', b'count', 3, b'number of passes to perform'),
2715 (b'', b'count', 3, b'number of passes to perform'),
2715 (b'', b'details', False, b'print timing for every revisions tested'),
2716 (b'', b'details', False, b'print timing for every revisions tested'),
2716 (b'', b'source', b'full', b'the kind of data feed in the revlog'),
2717 (b'', b'source', b'full', b'the kind of data feed in the revlog'),
2717 (b'', b'lazydeltabase', True, b'try the provided delta first'),
2718 (b'', b'lazydeltabase', True, b'try the provided delta first'),
2718 (b'', b'clear-caches', True, b'clear revlog cache between calls'),
2719 (b'', b'clear-caches', True, b'clear revlog cache between calls'),
2719 ],
2720 ],
2720 b'-c|-m|FILE',
2721 b'-c|-m|FILE',
2721 )
2722 )
2722 def perfrevlogwrite(ui, repo, file_=None, startrev=1000, stoprev=-1, **opts):
2723 def perfrevlogwrite(ui, repo, file_=None, startrev=1000, stoprev=-1, **opts):
2723 """Benchmark writing a series of revisions to a revlog.
2724 """Benchmark writing a series of revisions to a revlog.
2724
2725
2725 Possible source values are:
2726 Possible source values are:
2726 * `full`: add from a full text (default).
2727 * `full`: add from a full text (default).
2727 * `parent-1`: add from a delta to the first parent
2728 * `parent-1`: add from a delta to the first parent
2728 * `parent-2`: add from a delta to the second parent if it exists
2729 * `parent-2`: add from a delta to the second parent if it exists
2729 (use a delta from the first parent otherwise)
2730 (use a delta from the first parent otherwise)
2730 * `parent-smallest`: add from the smallest delta (either p1 or p2)
2731 * `parent-smallest`: add from the smallest delta (either p1 or p2)
2731 * `storage`: add from the existing precomputed deltas
2732 * `storage`: add from the existing precomputed deltas
2732
2733
2733 Note: This performance command measures performance in a custom way. As a
2734 Note: This performance command measures performance in a custom way. As a
2734 result some of the global configuration of the 'perf' command does not
2735 result some of the global configuration of the 'perf' command does not
2735 apply to it:
2736 apply to it:
2736
2737
2737 * ``pre-run``: disabled
2738 * ``pre-run``: disabled
2738
2739
2739 * ``profile-benchmark``: disabled
2740 * ``profile-benchmark``: disabled
2740
2741
2741 * ``run-limits``: disabled use --count instead
2742 * ``run-limits``: disabled use --count instead
2742 """
2743 """
2743 opts = _byteskwargs(opts)
2744 opts = _byteskwargs(opts)
2744
2745
2745 rl = cmdutil.openrevlog(repo, b'perfrevlogwrite', file_, opts)
2746 rl = cmdutil.openrevlog(repo, b'perfrevlogwrite', file_, opts)
2746 rllen = getlen(ui)(rl)
2747 rllen = getlen(ui)(rl)
2747 if startrev < 0:
2748 if startrev < 0:
2748 startrev = rllen + startrev
2749 startrev = rllen + startrev
2749 if stoprev < 0:
2750 if stoprev < 0:
2750 stoprev = rllen + stoprev
2751 stoprev = rllen + stoprev
2751
2752
2752 lazydeltabase = opts['lazydeltabase']
2753 lazydeltabase = opts['lazydeltabase']
2753 source = opts['source']
2754 source = opts['source']
2754 clearcaches = opts['clear_caches']
2755 clearcaches = opts['clear_caches']
2755 validsource = (
2756 validsource = (
2756 b'full',
2757 b'full',
2757 b'parent-1',
2758 b'parent-1',
2758 b'parent-2',
2759 b'parent-2',
2759 b'parent-smallest',
2760 b'parent-smallest',
2760 b'storage',
2761 b'storage',
2761 )
2762 )
2762 if source not in validsource:
2763 if source not in validsource:
2763 raise error.Abort('invalid source type: %s' % source)
2764 raise error.Abort('invalid source type: %s' % source)
2764
2765
2765 ### actually gather results
2766 ### actually gather results
2766 count = opts['count']
2767 count = opts['count']
2767 if count <= 0:
2768 if count <= 0:
2768 raise error.Abort('invalide run count: %d' % count)
2769 raise error.Abort('invalide run count: %d' % count)
2769 allresults = []
2770 allresults = []
2770 for c in range(count):
2771 for c in range(count):
2771 timing = _timeonewrite(
2772 timing = _timeonewrite(
2772 ui,
2773 ui,
2773 rl,
2774 rl,
2774 source,
2775 source,
2775 startrev,
2776 startrev,
2776 stoprev,
2777 stoprev,
2777 c + 1,
2778 c + 1,
2778 lazydeltabase=lazydeltabase,
2779 lazydeltabase=lazydeltabase,
2779 clearcaches=clearcaches,
2780 clearcaches=clearcaches,
2780 )
2781 )
2781 allresults.append(timing)
2782 allresults.append(timing)
2782
2783
2783 ### consolidate the results in a single list
2784 ### consolidate the results in a single list
2784 results = []
2785 results = []
2785 for idx, (rev, t) in enumerate(allresults[0]):
2786 for idx, (rev, t) in enumerate(allresults[0]):
2786 ts = [t]
2787 ts = [t]
2787 for other in allresults[1:]:
2788 for other in allresults[1:]:
2788 orev, ot = other[idx]
2789 orev, ot = other[idx]
2789 assert orev == rev
2790 assert orev == rev
2790 ts.append(ot)
2791 ts.append(ot)
2791 results.append((rev, ts))
2792 results.append((rev, ts))
2792 resultcount = len(results)
2793 resultcount = len(results)
2793
2794
2794 ### Compute and display relevant statistics
2795 ### Compute and display relevant statistics
2795
2796
2796 # get a formatter
2797 # get a formatter
2797 fm = ui.formatter(b'perf', opts)
2798 fm = ui.formatter(b'perf', opts)
2798 displayall = ui.configbool(b"perf", b"all-timing", False)
2799 displayall = ui.configbool(b"perf", b"all-timing", False)
2799
2800
2800 # print individual details if requested
2801 # print individual details if requested
2801 if opts['details']:
2802 if opts['details']:
2802 for idx, item in enumerate(results, 1):
2803 for idx, item in enumerate(results, 1):
2803 rev, data = item
2804 rev, data = item
2804 title = 'revisions #%d of %d, rev %d' % (idx, resultcount, rev)
2805 title = 'revisions #%d of %d, rev %d' % (idx, resultcount, rev)
2805 formatone(fm, data, title=title, displayall=displayall)
2806 formatone(fm, data, title=title, displayall=displayall)
2806
2807
2807 # sorts results by median time
2808 # sorts results by median time
2808 results.sort(key=lambda x: sorted(x[1])[len(x[1]) // 2])
2809 results.sort(key=lambda x: sorted(x[1])[len(x[1]) // 2])
2809 # list of (name, index) to display)
2810 # list of (name, index) to display)
2810 relevants = [
2811 relevants = [
2811 ("min", 0),
2812 ("min", 0),
2812 ("10%", resultcount * 10 // 100),
2813 ("10%", resultcount * 10 // 100),
2813 ("25%", resultcount * 25 // 100),
2814 ("25%", resultcount * 25 // 100),
2814 ("50%", resultcount * 70 // 100),
2815 ("50%", resultcount * 70 // 100),
2815 ("75%", resultcount * 75 // 100),
2816 ("75%", resultcount * 75 // 100),
2816 ("90%", resultcount * 90 // 100),
2817 ("90%", resultcount * 90 // 100),
2817 ("95%", resultcount * 95 // 100),
2818 ("95%", resultcount * 95 // 100),
2818 ("99%", resultcount * 99 // 100),
2819 ("99%", resultcount * 99 // 100),
2819 ("99.9%", resultcount * 999 // 1000),
2820 ("99.9%", resultcount * 999 // 1000),
2820 ("99.99%", resultcount * 9999 // 10000),
2821 ("99.99%", resultcount * 9999 // 10000),
2821 ("99.999%", resultcount * 99999 // 100000),
2822 ("99.999%", resultcount * 99999 // 100000),
2822 ("max", -1),
2823 ("max", -1),
2823 ]
2824 ]
2824 if not ui.quiet:
2825 if not ui.quiet:
2825 for name, idx in relevants:
2826 for name, idx in relevants:
2826 data = results[idx]
2827 data = results[idx]
2827 title = '%s of %d, rev %d' % (name, resultcount, data[0])
2828 title = '%s of %d, rev %d' % (name, resultcount, data[0])
2828 formatone(fm, data[1], title=title, displayall=displayall)
2829 formatone(fm, data[1], title=title, displayall=displayall)
2829
2830
2830 # XXX summing that many float will not be very precise, we ignore this fact
2831 # XXX summing that many float will not be very precise, we ignore this fact
2831 # for now
2832 # for now
2832 totaltime = []
2833 totaltime = []
2833 for item in allresults:
2834 for item in allresults:
2834 totaltime.append(
2835 totaltime.append(
2835 (
2836 (
2836 sum(x[1][0] for x in item),
2837 sum(x[1][0] for x in item),
2837 sum(x[1][1] for x in item),
2838 sum(x[1][1] for x in item),
2838 sum(x[1][2] for x in item),
2839 sum(x[1][2] for x in item),
2839 )
2840 )
2840 )
2841 )
2841 formatone(
2842 formatone(
2842 fm,
2843 fm,
2843 totaltime,
2844 totaltime,
2844 title="total time (%d revs)" % resultcount,
2845 title="total time (%d revs)" % resultcount,
2845 displayall=displayall,
2846 displayall=displayall,
2846 )
2847 )
2847 fm.end()
2848 fm.end()
2848
2849
2849
2850
2850 class _faketr(object):
2851 class _faketr(object):
2851 def add(s, x, y, z=None):
2852 def add(s, x, y, z=None):
2852 return None
2853 return None
2853
2854
2854
2855
2855 def _timeonewrite(
2856 def _timeonewrite(
2856 ui,
2857 ui,
2857 orig,
2858 orig,
2858 source,
2859 source,
2859 startrev,
2860 startrev,
2860 stoprev,
2861 stoprev,
2861 runidx=None,
2862 runidx=None,
2862 lazydeltabase=True,
2863 lazydeltabase=True,
2863 clearcaches=True,
2864 clearcaches=True,
2864 ):
2865 ):
2865 timings = []
2866 timings = []
2866 tr = _faketr()
2867 tr = _faketr()
2867 with _temprevlog(ui, orig, startrev) as dest:
2868 with _temprevlog(ui, orig, startrev) as dest:
2868 dest._lazydeltabase = lazydeltabase
2869 dest._lazydeltabase = lazydeltabase
2869 revs = list(orig.revs(startrev, stoprev))
2870 revs = list(orig.revs(startrev, stoprev))
2870 total = len(revs)
2871 total = len(revs)
2871 topic = 'adding'
2872 topic = 'adding'
2872 if runidx is not None:
2873 if runidx is not None:
2873 topic += ' (run #%d)' % runidx
2874 topic += ' (run #%d)' % runidx
2874 # Support both old and new progress API
2875 # Support both old and new progress API
2875 if util.safehasattr(ui, 'makeprogress'):
2876 if util.safehasattr(ui, 'makeprogress'):
2876 progress = ui.makeprogress(topic, unit='revs', total=total)
2877 progress = ui.makeprogress(topic, unit='revs', total=total)
2877
2878
2878 def updateprogress(pos):
2879 def updateprogress(pos):
2879 progress.update(pos)
2880 progress.update(pos)
2880
2881
2881 def completeprogress():
2882 def completeprogress():
2882 progress.complete()
2883 progress.complete()
2883
2884
2884 else:
2885 else:
2885
2886
2886 def updateprogress(pos):
2887 def updateprogress(pos):
2887 ui.progress(topic, pos, unit='revs', total=total)
2888 ui.progress(topic, pos, unit='revs', total=total)
2888
2889
2889 def completeprogress():
2890 def completeprogress():
2890 ui.progress(topic, None, unit='revs', total=total)
2891 ui.progress(topic, None, unit='revs', total=total)
2891
2892
2892 for idx, rev in enumerate(revs):
2893 for idx, rev in enumerate(revs):
2893 updateprogress(idx)
2894 updateprogress(idx)
2894 addargs, addkwargs = _getrevisionseed(orig, rev, tr, source)
2895 addargs, addkwargs = _getrevisionseed(orig, rev, tr, source)
2895 if clearcaches:
2896 if clearcaches:
2896 dest.index.clearcaches()
2897 dest.index.clearcaches()
2897 dest.clearcaches()
2898 dest.clearcaches()
2898 with timeone() as r:
2899 with timeone() as r:
2899 dest.addrawrevision(*addargs, **addkwargs)
2900 dest.addrawrevision(*addargs, **addkwargs)
2900 timings.append((rev, r[0]))
2901 timings.append((rev, r[0]))
2901 updateprogress(total)
2902 updateprogress(total)
2902 completeprogress()
2903 completeprogress()
2903 return timings
2904 return timings
2904
2905
2905
2906
2906 def _getrevisionseed(orig, rev, tr, source):
2907 def _getrevisionseed(orig, rev, tr, source):
2907 from mercurial.node import nullid
2908 from mercurial.node import nullid
2908
2909
2909 linkrev = orig.linkrev(rev)
2910 linkrev = orig.linkrev(rev)
2910 node = orig.node(rev)
2911 node = orig.node(rev)
2911 p1, p2 = orig.parents(node)
2912 p1, p2 = orig.parents(node)
2912 flags = orig.flags(rev)
2913 flags = orig.flags(rev)
2913 cachedelta = None
2914 cachedelta = None
2914 text = None
2915 text = None
2915
2916
2916 if source == b'full':
2917 if source == b'full':
2917 text = orig.revision(rev)
2918 text = orig.revision(rev)
2918 elif source == b'parent-1':
2919 elif source == b'parent-1':
2919 baserev = orig.rev(p1)
2920 baserev = orig.rev(p1)
2920 cachedelta = (baserev, orig.revdiff(p1, rev))
2921 cachedelta = (baserev, orig.revdiff(p1, rev))
2921 elif source == b'parent-2':
2922 elif source == b'parent-2':
2922 parent = p2
2923 parent = p2
2923 if p2 == nullid:
2924 if p2 == nullid:
2924 parent = p1
2925 parent = p1
2925 baserev = orig.rev(parent)
2926 baserev = orig.rev(parent)
2926 cachedelta = (baserev, orig.revdiff(parent, rev))
2927 cachedelta = (baserev, orig.revdiff(parent, rev))
2927 elif source == b'parent-smallest':
2928 elif source == b'parent-smallest':
2928 p1diff = orig.revdiff(p1, rev)
2929 p1diff = orig.revdiff(p1, rev)
2929 parent = p1
2930 parent = p1
2930 diff = p1diff
2931 diff = p1diff
2931 if p2 != nullid:
2932 if p2 != nullid:
2932 p2diff = orig.revdiff(p2, rev)
2933 p2diff = orig.revdiff(p2, rev)
2933 if len(p1diff) > len(p2diff):
2934 if len(p1diff) > len(p2diff):
2934 parent = p2
2935 parent = p2
2935 diff = p2diff
2936 diff = p2diff
2936 baserev = orig.rev(parent)
2937 baserev = orig.rev(parent)
2937 cachedelta = (baserev, diff)
2938 cachedelta = (baserev, diff)
2938 elif source == b'storage':
2939 elif source == b'storage':
2939 baserev = orig.deltaparent(rev)
2940 baserev = orig.deltaparent(rev)
2940 cachedelta = (baserev, orig.revdiff(orig.node(baserev), rev))
2941 cachedelta = (baserev, orig.revdiff(orig.node(baserev), rev))
2941
2942
2942 return (
2943 return (
2943 (text, tr, linkrev, p1, p2),
2944 (text, tr, linkrev, p1, p2),
2944 {'node': node, 'flags': flags, 'cachedelta': cachedelta},
2945 {'node': node, 'flags': flags, 'cachedelta': cachedelta},
2945 )
2946 )
2946
2947
2947
2948
2948 @contextlib.contextmanager
2949 @contextlib.contextmanager
2949 def _temprevlog(ui, orig, truncaterev):
2950 def _temprevlog(ui, orig, truncaterev):
2950 from mercurial import vfs as vfsmod
2951 from mercurial import vfs as vfsmod
2951
2952
2952 if orig._inline:
2953 if orig._inline:
2953 raise error.Abort('not supporting inline revlog (yet)')
2954 raise error.Abort('not supporting inline revlog (yet)')
2954 revlogkwargs = {}
2955 revlogkwargs = {}
2955 k = 'upperboundcomp'
2956 k = 'upperboundcomp'
2956 if util.safehasattr(orig, k):
2957 if util.safehasattr(orig, k):
2957 revlogkwargs[k] = getattr(orig, k)
2958 revlogkwargs[k] = getattr(orig, k)
2958
2959
2959 origindexpath = orig.opener.join(orig.indexfile)
2960 origindexpath = orig.opener.join(orig.indexfile)
2960 origdatapath = orig.opener.join(orig.datafile)
2961 origdatapath = orig.opener.join(orig.datafile)
2961 indexname = 'revlog.i'
2962 indexname = 'revlog.i'
2962 dataname = 'revlog.d'
2963 dataname = 'revlog.d'
2963
2964
2964 tmpdir = tempfile.mkdtemp(prefix='tmp-hgperf-')
2965 tmpdir = tempfile.mkdtemp(prefix='tmp-hgperf-')
2965 try:
2966 try:
2966 # copy the data file in a temporary directory
2967 # copy the data file in a temporary directory
2967 ui.debug('copying data in %s\n' % tmpdir)
2968 ui.debug('copying data in %s\n' % tmpdir)
2968 destindexpath = os.path.join(tmpdir, 'revlog.i')
2969 destindexpath = os.path.join(tmpdir, 'revlog.i')
2969 destdatapath = os.path.join(tmpdir, 'revlog.d')
2970 destdatapath = os.path.join(tmpdir, 'revlog.d')
2970 shutil.copyfile(origindexpath, destindexpath)
2971 shutil.copyfile(origindexpath, destindexpath)
2971 shutil.copyfile(origdatapath, destdatapath)
2972 shutil.copyfile(origdatapath, destdatapath)
2972
2973
2973 # remove the data we want to add again
2974 # remove the data we want to add again
2974 ui.debug('truncating data to be rewritten\n')
2975 ui.debug('truncating data to be rewritten\n')
2975 with open(destindexpath, 'ab') as index:
2976 with open(destindexpath, 'ab') as index:
2976 index.seek(0)
2977 index.seek(0)
2977 index.truncate(truncaterev * orig._io.size)
2978 index.truncate(truncaterev * orig._io.size)
2978 with open(destdatapath, 'ab') as data:
2979 with open(destdatapath, 'ab') as data:
2979 data.seek(0)
2980 data.seek(0)
2980 data.truncate(orig.start(truncaterev))
2981 data.truncate(orig.start(truncaterev))
2981
2982
2982 # instantiate a new revlog from the temporary copy
2983 # instantiate a new revlog from the temporary copy
2983 ui.debug('truncating adding to be rewritten\n')
2984 ui.debug('truncating adding to be rewritten\n')
2984 vfs = vfsmod.vfs(tmpdir)
2985 vfs = vfsmod.vfs(tmpdir)
2985 vfs.options = getattr(orig.opener, 'options', None)
2986 vfs.options = getattr(orig.opener, 'options', None)
2986
2987
2987 dest = revlog.revlog(
2988 dest = revlog.revlog(
2988 vfs, indexfile=indexname, datafile=dataname, **revlogkwargs
2989 vfs, indexfile=indexname, datafile=dataname, **revlogkwargs
2989 )
2990 )
2990 if dest._inline:
2991 if dest._inline:
2991 raise error.Abort('not supporting inline revlog (yet)')
2992 raise error.Abort('not supporting inline revlog (yet)')
2992 # make sure internals are initialized
2993 # make sure internals are initialized
2993 dest.revision(len(dest) - 1)
2994 dest.revision(len(dest) - 1)
2994 yield dest
2995 yield dest
2995 del dest, vfs
2996 del dest, vfs
2996 finally:
2997 finally:
2997 shutil.rmtree(tmpdir, True)
2998 shutil.rmtree(tmpdir, True)
2998
2999
2999
3000
3000 @command(
3001 @command(
3001 b'perfrevlogchunks',
3002 b'perfrevlogchunks',
3002 revlogopts
3003 revlogopts
3003 + formatteropts
3004 + formatteropts
3004 + [
3005 + [
3005 (b'e', b'engines', b'', b'compression engines to use'),
3006 (b'e', b'engines', b'', b'compression engines to use'),
3006 (b's', b'startrev', 0, b'revision to start at'),
3007 (b's', b'startrev', 0, b'revision to start at'),
3007 ],
3008 ],
3008 b'-c|-m|FILE',
3009 b'-c|-m|FILE',
3009 )
3010 )
3010 def perfrevlogchunks(ui, repo, file_=None, engines=None, startrev=0, **opts):
3011 def perfrevlogchunks(ui, repo, file_=None, engines=None, startrev=0, **opts):
3011 """Benchmark operations on revlog chunks.
3012 """Benchmark operations on revlog chunks.
3012
3013
3013 Logically, each revlog is a collection of fulltext revisions. However,
3014 Logically, each revlog is a collection of fulltext revisions. However,
3014 stored within each revlog are "chunks" of possibly compressed data. This
3015 stored within each revlog are "chunks" of possibly compressed data. This
3015 data needs to be read and decompressed or compressed and written.
3016 data needs to be read and decompressed or compressed and written.
3016
3017
3017 This command measures the time it takes to read+decompress and recompress
3018 This command measures the time it takes to read+decompress and recompress
3018 chunks in a revlog. It effectively isolates I/O and compression performance.
3019 chunks in a revlog. It effectively isolates I/O and compression performance.
3019 For measurements of higher-level operations like resolving revisions,
3020 For measurements of higher-level operations like resolving revisions,
3020 see ``perfrevlogrevisions`` and ``perfrevlogrevision``.
3021 see ``perfrevlogrevisions`` and ``perfrevlogrevision``.
3021 """
3022 """
3022 opts = _byteskwargs(opts)
3023 opts = _byteskwargs(opts)
3023
3024
3024 rl = cmdutil.openrevlog(repo, b'perfrevlogchunks', file_, opts)
3025 rl = cmdutil.openrevlog(repo, b'perfrevlogchunks', file_, opts)
3025
3026
3026 # _chunkraw was renamed to _getsegmentforrevs.
3027 # _chunkraw was renamed to _getsegmentforrevs.
3027 try:
3028 try:
3028 segmentforrevs = rl._getsegmentforrevs
3029 segmentforrevs = rl._getsegmentforrevs
3029 except AttributeError:
3030 except AttributeError:
3030 segmentforrevs = rl._chunkraw
3031 segmentforrevs = rl._chunkraw
3031
3032
3032 # Verify engines argument.
3033 # Verify engines argument.
3033 if engines:
3034 if engines:
3034 engines = set(e.strip() for e in engines.split(b','))
3035 engines = set(e.strip() for e in engines.split(b','))
3035 for engine in engines:
3036 for engine in engines:
3036 try:
3037 try:
3037 util.compressionengines[engine]
3038 util.compressionengines[engine]
3038 except KeyError:
3039 except KeyError:
3039 raise error.Abort(b'unknown compression engine: %s' % engine)
3040 raise error.Abort(b'unknown compression engine: %s' % engine)
3040 else:
3041 else:
3041 engines = []
3042 engines = []
3042 for e in util.compengines:
3043 for e in util.compengines:
3043 engine = util.compengines[e]
3044 engine = util.compengines[e]
3044 try:
3045 try:
3045 if engine.available():
3046 if engine.available():
3046 engine.revlogcompressor().compress(b'dummy')
3047 engine.revlogcompressor().compress(b'dummy')
3047 engines.append(e)
3048 engines.append(e)
3048 except NotImplementedError:
3049 except NotImplementedError:
3049 pass
3050 pass
3050
3051
3051 revs = list(rl.revs(startrev, len(rl) - 1))
3052 revs = list(rl.revs(startrev, len(rl) - 1))
3052
3053
3053 def rlfh(rl):
3054 def rlfh(rl):
3054 if rl._inline:
3055 if rl._inline:
3055 return getsvfs(repo)(rl.indexfile)
3056 return getsvfs(repo)(rl.indexfile)
3056 else:
3057 else:
3057 return getsvfs(repo)(rl.datafile)
3058 return getsvfs(repo)(rl.datafile)
3058
3059
3059 def doread():
3060 def doread():
3060 rl.clearcaches()
3061 rl.clearcaches()
3061 for rev in revs:
3062 for rev in revs:
3062 segmentforrevs(rev, rev)
3063 segmentforrevs(rev, rev)
3063
3064
3064 def doreadcachedfh():
3065 def doreadcachedfh():
3065 rl.clearcaches()
3066 rl.clearcaches()
3066 fh = rlfh(rl)
3067 fh = rlfh(rl)
3067 for rev in revs:
3068 for rev in revs:
3068 segmentforrevs(rev, rev, df=fh)
3069 segmentforrevs(rev, rev, df=fh)
3069
3070
3070 def doreadbatch():
3071 def doreadbatch():
3071 rl.clearcaches()
3072 rl.clearcaches()
3072 segmentforrevs(revs[0], revs[-1])
3073 segmentforrevs(revs[0], revs[-1])
3073
3074
3074 def doreadbatchcachedfh():
3075 def doreadbatchcachedfh():
3075 rl.clearcaches()
3076 rl.clearcaches()
3076 fh = rlfh(rl)
3077 fh = rlfh(rl)
3077 segmentforrevs(revs[0], revs[-1], df=fh)
3078 segmentforrevs(revs[0], revs[-1], df=fh)
3078
3079
3079 def dochunk():
3080 def dochunk():
3080 rl.clearcaches()
3081 rl.clearcaches()
3081 fh = rlfh(rl)
3082 fh = rlfh(rl)
3082 for rev in revs:
3083 for rev in revs:
3083 rl._chunk(rev, df=fh)
3084 rl._chunk(rev, df=fh)
3084
3085
3085 chunks = [None]
3086 chunks = [None]
3086
3087
3087 def dochunkbatch():
3088 def dochunkbatch():
3088 rl.clearcaches()
3089 rl.clearcaches()
3089 fh = rlfh(rl)
3090 fh = rlfh(rl)
3090 # Save chunks as a side-effect.
3091 # Save chunks as a side-effect.
3091 chunks[0] = rl._chunks(revs, df=fh)
3092 chunks[0] = rl._chunks(revs, df=fh)
3092
3093
3093 def docompress(compressor):
3094 def docompress(compressor):
3094 rl.clearcaches()
3095 rl.clearcaches()
3095
3096
3096 try:
3097 try:
3097 # Swap in the requested compression engine.
3098 # Swap in the requested compression engine.
3098 oldcompressor = rl._compressor
3099 oldcompressor = rl._compressor
3099 rl._compressor = compressor
3100 rl._compressor = compressor
3100 for chunk in chunks[0]:
3101 for chunk in chunks[0]:
3101 rl.compress(chunk)
3102 rl.compress(chunk)
3102 finally:
3103 finally:
3103 rl._compressor = oldcompressor
3104 rl._compressor = oldcompressor
3104
3105
3105 benches = [
3106 benches = [
3106 (lambda: doread(), b'read'),
3107 (lambda: doread(), b'read'),
3107 (lambda: doreadcachedfh(), b'read w/ reused fd'),
3108 (lambda: doreadcachedfh(), b'read w/ reused fd'),
3108 (lambda: doreadbatch(), b'read batch'),
3109 (lambda: doreadbatch(), b'read batch'),
3109 (lambda: doreadbatchcachedfh(), b'read batch w/ reused fd'),
3110 (lambda: doreadbatchcachedfh(), b'read batch w/ reused fd'),
3110 (lambda: dochunk(), b'chunk'),
3111 (lambda: dochunk(), b'chunk'),
3111 (lambda: dochunkbatch(), b'chunk batch'),
3112 (lambda: dochunkbatch(), b'chunk batch'),
3112 ]
3113 ]
3113
3114
3114 for engine in sorted(engines):
3115 for engine in sorted(engines):
3115 compressor = util.compengines[engine].revlogcompressor()
3116 compressor = util.compengines[engine].revlogcompressor()
3116 benches.append(
3117 benches.append(
3117 (
3118 (
3118 functools.partial(docompress, compressor),
3119 functools.partial(docompress, compressor),
3119 b'compress w/ %s' % engine,
3120 b'compress w/ %s' % engine,
3120 )
3121 )
3121 )
3122 )
3122
3123
3123 for fn, title in benches:
3124 for fn, title in benches:
3124 timer, fm = gettimer(ui, opts)
3125 timer, fm = gettimer(ui, opts)
3125 timer(fn, title=title)
3126 timer(fn, title=title)
3126 fm.end()
3127 fm.end()
3127
3128
3128
3129
3129 @command(
3130 @command(
3130 b'perfrevlogrevision',
3131 b'perfrevlogrevision',
3131 revlogopts
3132 revlogopts
3132 + formatteropts
3133 + formatteropts
3133 + [(b'', b'cache', False, b'use caches instead of clearing')],
3134 + [(b'', b'cache', False, b'use caches instead of clearing')],
3134 b'-c|-m|FILE REV',
3135 b'-c|-m|FILE REV',
3135 )
3136 )
3136 def perfrevlogrevision(ui, repo, file_, rev=None, cache=None, **opts):
3137 def perfrevlogrevision(ui, repo, file_, rev=None, cache=None, **opts):
3137 """Benchmark obtaining a revlog revision.
3138 """Benchmark obtaining a revlog revision.
3138
3139
3139 Obtaining a revlog revision consists of roughly the following steps:
3140 Obtaining a revlog revision consists of roughly the following steps:
3140
3141
3141 1. Compute the delta chain
3142 1. Compute the delta chain
3142 2. Slice the delta chain if applicable
3143 2. Slice the delta chain if applicable
3143 3. Obtain the raw chunks for that delta chain
3144 3. Obtain the raw chunks for that delta chain
3144 4. Decompress each raw chunk
3145 4. Decompress each raw chunk
3145 5. Apply binary patches to obtain fulltext
3146 5. Apply binary patches to obtain fulltext
3146 6. Verify hash of fulltext
3147 6. Verify hash of fulltext
3147
3148
3148 This command measures the time spent in each of these phases.
3149 This command measures the time spent in each of these phases.
3149 """
3150 """
3150 opts = _byteskwargs(opts)
3151 opts = _byteskwargs(opts)
3151
3152
3152 if opts.get(b'changelog') or opts.get(b'manifest'):
3153 if opts.get(b'changelog') or opts.get(b'manifest'):
3153 file_, rev = None, file_
3154 file_, rev = None, file_
3154 elif rev is None:
3155 elif rev is None:
3155 raise error.CommandError(b'perfrevlogrevision', b'invalid arguments')
3156 raise error.CommandError(b'perfrevlogrevision', b'invalid arguments')
3156
3157
3157 r = cmdutil.openrevlog(repo, b'perfrevlogrevision', file_, opts)
3158 r = cmdutil.openrevlog(repo, b'perfrevlogrevision', file_, opts)
3158
3159
3159 # _chunkraw was renamed to _getsegmentforrevs.
3160 # _chunkraw was renamed to _getsegmentforrevs.
3160 try:
3161 try:
3161 segmentforrevs = r._getsegmentforrevs
3162 segmentforrevs = r._getsegmentforrevs
3162 except AttributeError:
3163 except AttributeError:
3163 segmentforrevs = r._chunkraw
3164 segmentforrevs = r._chunkraw
3164
3165
3165 node = r.lookup(rev)
3166 node = r.lookup(rev)
3166 rev = r.rev(node)
3167 rev = r.rev(node)
3167
3168
3168 def getrawchunks(data, chain):
3169 def getrawchunks(data, chain):
3169 start = r.start
3170 start = r.start
3170 length = r.length
3171 length = r.length
3171 inline = r._inline
3172 inline = r._inline
3172 iosize = r._io.size
3173 iosize = r._io.size
3173 buffer = util.buffer
3174 buffer = util.buffer
3174
3175
3175 chunks = []
3176 chunks = []
3176 ladd = chunks.append
3177 ladd = chunks.append
3177 for idx, item in enumerate(chain):
3178 for idx, item in enumerate(chain):
3178 offset = start(item[0])
3179 offset = start(item[0])
3179 bits = data[idx]
3180 bits = data[idx]
3180 for rev in item:
3181 for rev in item:
3181 chunkstart = start(rev)
3182 chunkstart = start(rev)
3182 if inline:
3183 if inline:
3183 chunkstart += (rev + 1) * iosize
3184 chunkstart += (rev + 1) * iosize
3184 chunklength = length(rev)
3185 chunklength = length(rev)
3185 ladd(buffer(bits, chunkstart - offset, chunklength))
3186 ladd(buffer(bits, chunkstart - offset, chunklength))
3186
3187
3187 return chunks
3188 return chunks
3188
3189
3189 def dodeltachain(rev):
3190 def dodeltachain(rev):
3190 if not cache:
3191 if not cache:
3191 r.clearcaches()
3192 r.clearcaches()
3192 r._deltachain(rev)
3193 r._deltachain(rev)
3193
3194
3194 def doread(chain):
3195 def doread(chain):
3195 if not cache:
3196 if not cache:
3196 r.clearcaches()
3197 r.clearcaches()
3197 for item in slicedchain:
3198 for item in slicedchain:
3198 segmentforrevs(item[0], item[-1])
3199 segmentforrevs(item[0], item[-1])
3199
3200
3200 def doslice(r, chain, size):
3201 def doslice(r, chain, size):
3201 for s in slicechunk(r, chain, targetsize=size):
3202 for s in slicechunk(r, chain, targetsize=size):
3202 pass
3203 pass
3203
3204
3204 def dorawchunks(data, chain):
3205 def dorawchunks(data, chain):
3205 if not cache:
3206 if not cache:
3206 r.clearcaches()
3207 r.clearcaches()
3207 getrawchunks(data, chain)
3208 getrawchunks(data, chain)
3208
3209
3209 def dodecompress(chunks):
3210 def dodecompress(chunks):
3210 decomp = r.decompress
3211 decomp = r.decompress
3211 for chunk in chunks:
3212 for chunk in chunks:
3212 decomp(chunk)
3213 decomp(chunk)
3213
3214
3214 def dopatch(text, bins):
3215 def dopatch(text, bins):
3215 if not cache:
3216 if not cache:
3216 r.clearcaches()
3217 r.clearcaches()
3217 mdiff.patches(text, bins)
3218 mdiff.patches(text, bins)
3218
3219
3219 def dohash(text):
3220 def dohash(text):
3220 if not cache:
3221 if not cache:
3221 r.clearcaches()
3222 r.clearcaches()
3222 r.checkhash(text, node, rev=rev)
3223 r.checkhash(text, node, rev=rev)
3223
3224
3224 def dorevision():
3225 def dorevision():
3225 if not cache:
3226 if not cache:
3226 r.clearcaches()
3227 r.clearcaches()
3227 r.revision(node)
3228 r.revision(node)
3228
3229
3229 try:
3230 try:
3230 from mercurial.revlogutils.deltas import slicechunk
3231 from mercurial.revlogutils.deltas import slicechunk
3231 except ImportError:
3232 except ImportError:
3232 slicechunk = getattr(revlog, '_slicechunk', None)
3233 slicechunk = getattr(revlog, '_slicechunk', None)
3233
3234
3234 size = r.length(rev)
3235 size = r.length(rev)
3235 chain = r._deltachain(rev)[0]
3236 chain = r._deltachain(rev)[0]
3236 if not getattr(r, '_withsparseread', False):
3237 if not getattr(r, '_withsparseread', False):
3237 slicedchain = (chain,)
3238 slicedchain = (chain,)
3238 else:
3239 else:
3239 slicedchain = tuple(slicechunk(r, chain, targetsize=size))
3240 slicedchain = tuple(slicechunk(r, chain, targetsize=size))
3240 data = [segmentforrevs(seg[0], seg[-1])[1] for seg in slicedchain]
3241 data = [segmentforrevs(seg[0], seg[-1])[1] for seg in slicedchain]
3241 rawchunks = getrawchunks(data, slicedchain)
3242 rawchunks = getrawchunks(data, slicedchain)
3242 bins = r._chunks(chain)
3243 bins = r._chunks(chain)
3243 text = bytes(bins[0])
3244 text = bytes(bins[0])
3244 bins = bins[1:]
3245 bins = bins[1:]
3245 text = mdiff.patches(text, bins)
3246 text = mdiff.patches(text, bins)
3246
3247
3247 benches = [
3248 benches = [
3248 (lambda: dorevision(), b'full'),
3249 (lambda: dorevision(), b'full'),
3249 (lambda: dodeltachain(rev), b'deltachain'),
3250 (lambda: dodeltachain(rev), b'deltachain'),
3250 (lambda: doread(chain), b'read'),
3251 (lambda: doread(chain), b'read'),
3251 ]
3252 ]
3252
3253
3253 if getattr(r, '_withsparseread', False):
3254 if getattr(r, '_withsparseread', False):
3254 slicing = (lambda: doslice(r, chain, size), b'slice-sparse-chain')
3255 slicing = (lambda: doslice(r, chain, size), b'slice-sparse-chain')
3255 benches.append(slicing)
3256 benches.append(slicing)
3256
3257
3257 benches.extend(
3258 benches.extend(
3258 [
3259 [
3259 (lambda: dorawchunks(data, slicedchain), b'rawchunks'),
3260 (lambda: dorawchunks(data, slicedchain), b'rawchunks'),
3260 (lambda: dodecompress(rawchunks), b'decompress'),
3261 (lambda: dodecompress(rawchunks), b'decompress'),
3261 (lambda: dopatch(text, bins), b'patch'),
3262 (lambda: dopatch(text, bins), b'patch'),
3262 (lambda: dohash(text), b'hash'),
3263 (lambda: dohash(text), b'hash'),
3263 ]
3264 ]
3264 )
3265 )
3265
3266
3266 timer, fm = gettimer(ui, opts)
3267 timer, fm = gettimer(ui, opts)
3267 for fn, title in benches:
3268 for fn, title in benches:
3268 timer(fn, title=title)
3269 timer(fn, title=title)
3269 fm.end()
3270 fm.end()
3270
3271
3271
3272
3272 @command(
3273 @command(
3273 b'perfrevset',
3274 b'perfrevset',
3274 [
3275 [
3275 (b'C', b'clear', False, b'clear volatile cache between each call.'),
3276 (b'C', b'clear', False, b'clear volatile cache between each call.'),
3276 (b'', b'contexts', False, b'obtain changectx for each revision'),
3277 (b'', b'contexts', False, b'obtain changectx for each revision'),
3277 ]
3278 ]
3278 + formatteropts,
3279 + formatteropts,
3279 b"REVSET",
3280 b"REVSET",
3280 )
3281 )
3281 def perfrevset(ui, repo, expr, clear=False, contexts=False, **opts):
3282 def perfrevset(ui, repo, expr, clear=False, contexts=False, **opts):
3282 """benchmark the execution time of a revset
3283 """benchmark the execution time of a revset
3283
3284
3284 Use the --clean option if need to evaluate the impact of build volatile
3285 Use the --clean option if need to evaluate the impact of build volatile
3285 revisions set cache on the revset execution. Volatile cache hold filtered
3286 revisions set cache on the revset execution. Volatile cache hold filtered
3286 and obsolete related cache."""
3287 and obsolete related cache."""
3287 opts = _byteskwargs(opts)
3288 opts = _byteskwargs(opts)
3288
3289
3289 timer, fm = gettimer(ui, opts)
3290 timer, fm = gettimer(ui, opts)
3290
3291
3291 def d():
3292 def d():
3292 if clear:
3293 if clear:
3293 repo.invalidatevolatilesets()
3294 repo.invalidatevolatilesets()
3294 if contexts:
3295 if contexts:
3295 for ctx in repo.set(expr):
3296 for ctx in repo.set(expr):
3296 pass
3297 pass
3297 else:
3298 else:
3298 for r in repo.revs(expr):
3299 for r in repo.revs(expr):
3299 pass
3300 pass
3300
3301
3301 timer(d)
3302 timer(d)
3302 fm.end()
3303 fm.end()
3303
3304
3304
3305
3305 @command(
3306 @command(
3306 b'perfvolatilesets',
3307 b'perfvolatilesets',
3307 [(b'', b'clear-obsstore', False, b'drop obsstore between each call.'),]
3308 [(b'', b'clear-obsstore', False, b'drop obsstore between each call.'),]
3308 + formatteropts,
3309 + formatteropts,
3309 )
3310 )
3310 def perfvolatilesets(ui, repo, *names, **opts):
3311 def perfvolatilesets(ui, repo, *names, **opts):
3311 """benchmark the computation of various volatile set
3312 """benchmark the computation of various volatile set
3312
3313
3313 Volatile set computes element related to filtering and obsolescence."""
3314 Volatile set computes element related to filtering and obsolescence."""
3314 opts = _byteskwargs(opts)
3315 opts = _byteskwargs(opts)
3315 timer, fm = gettimer(ui, opts)
3316 timer, fm = gettimer(ui, opts)
3316 repo = repo.unfiltered()
3317 repo = repo.unfiltered()
3317
3318
3318 def getobs(name):
3319 def getobs(name):
3319 def d():
3320 def d():
3320 repo.invalidatevolatilesets()
3321 repo.invalidatevolatilesets()
3321 if opts[b'clear_obsstore']:
3322 if opts[b'clear_obsstore']:
3322 clearfilecache(repo, b'obsstore')
3323 clearfilecache(repo, b'obsstore')
3323 obsolete.getrevs(repo, name)
3324 obsolete.getrevs(repo, name)
3324
3325
3325 return d
3326 return d
3326
3327
3327 allobs = sorted(obsolete.cachefuncs)
3328 allobs = sorted(obsolete.cachefuncs)
3328 if names:
3329 if names:
3329 allobs = [n for n in allobs if n in names]
3330 allobs = [n for n in allobs if n in names]
3330
3331
3331 for name in allobs:
3332 for name in allobs:
3332 timer(getobs(name), title=name)
3333 timer(getobs(name), title=name)
3333
3334
3334 def getfiltered(name):
3335 def getfiltered(name):
3335 def d():
3336 def d():
3336 repo.invalidatevolatilesets()
3337 repo.invalidatevolatilesets()
3337 if opts[b'clear_obsstore']:
3338 if opts[b'clear_obsstore']:
3338 clearfilecache(repo, b'obsstore')
3339 clearfilecache(repo, b'obsstore')
3339 repoview.filterrevs(repo, name)
3340 repoview.filterrevs(repo, name)
3340
3341
3341 return d
3342 return d
3342
3343
3343 allfilter = sorted(repoview.filtertable)
3344 allfilter = sorted(repoview.filtertable)
3344 if names:
3345 if names:
3345 allfilter = [n for n in allfilter if n in names]
3346 allfilter = [n for n in allfilter if n in names]
3346
3347
3347 for name in allfilter:
3348 for name in allfilter:
3348 timer(getfiltered(name), title=name)
3349 timer(getfiltered(name), title=name)
3349 fm.end()
3350 fm.end()
3350
3351
3351
3352
3352 @command(
3353 @command(
3353 b'perfbranchmap',
3354 b'perfbranchmap',
3354 [
3355 [
3355 (b'f', b'full', False, b'Includes build time of subset'),
3356 (b'f', b'full', False, b'Includes build time of subset'),
3356 (
3357 (
3357 b'',
3358 b'',
3358 b'clear-revbranch',
3359 b'clear-revbranch',
3359 False,
3360 False,
3360 b'purge the revbranch cache between computation',
3361 b'purge the revbranch cache between computation',
3361 ),
3362 ),
3362 ]
3363 ]
3363 + formatteropts,
3364 + formatteropts,
3364 )
3365 )
3365 def perfbranchmap(ui, repo, *filternames, **opts):
3366 def perfbranchmap(ui, repo, *filternames, **opts):
3366 """benchmark the update of a branchmap
3367 """benchmark the update of a branchmap
3367
3368
3368 This benchmarks the full repo.branchmap() call with read and write disabled
3369 This benchmarks the full repo.branchmap() call with read and write disabled
3369 """
3370 """
3370 opts = _byteskwargs(opts)
3371 opts = _byteskwargs(opts)
3371 full = opts.get(b"full", False)
3372 full = opts.get(b"full", False)
3372 clear_revbranch = opts.get(b"clear_revbranch", False)
3373 clear_revbranch = opts.get(b"clear_revbranch", False)
3373 timer, fm = gettimer(ui, opts)
3374 timer, fm = gettimer(ui, opts)
3374
3375
3375 def getbranchmap(filtername):
3376 def getbranchmap(filtername):
3376 """generate a benchmark function for the filtername"""
3377 """generate a benchmark function for the filtername"""
3377 if filtername is None:
3378 if filtername is None:
3378 view = repo
3379 view = repo
3379 else:
3380 else:
3380 view = repo.filtered(filtername)
3381 view = repo.filtered(filtername)
3381 if util.safehasattr(view._branchcaches, '_per_filter'):
3382 if util.safehasattr(view._branchcaches, '_per_filter'):
3382 filtered = view._branchcaches._per_filter
3383 filtered = view._branchcaches._per_filter
3383 else:
3384 else:
3384 # older versions
3385 # older versions
3385 filtered = view._branchcaches
3386 filtered = view._branchcaches
3386
3387
3387 def d():
3388 def d():
3388 if clear_revbranch:
3389 if clear_revbranch:
3389 repo.revbranchcache()._clear()
3390 repo.revbranchcache()._clear()
3390 if full:
3391 if full:
3391 view._branchcaches.clear()
3392 view._branchcaches.clear()
3392 else:
3393 else:
3393 filtered.pop(filtername, None)
3394 filtered.pop(filtername, None)
3394 view.branchmap()
3395 view.branchmap()
3395
3396
3396 return d
3397 return d
3397
3398
3398 # add filter in smaller subset to bigger subset
3399 # add filter in smaller subset to bigger subset
3399 possiblefilters = set(repoview.filtertable)
3400 possiblefilters = set(repoview.filtertable)
3400 if filternames:
3401 if filternames:
3401 possiblefilters &= set(filternames)
3402 possiblefilters &= set(filternames)
3402 subsettable = getbranchmapsubsettable()
3403 subsettable = getbranchmapsubsettable()
3403 allfilters = []
3404 allfilters = []
3404 while possiblefilters:
3405 while possiblefilters:
3405 for name in possiblefilters:
3406 for name in possiblefilters:
3406 subset = subsettable.get(name)
3407 subset = subsettable.get(name)
3407 if subset not in possiblefilters:
3408 if subset not in possiblefilters:
3408 break
3409 break
3409 else:
3410 else:
3410 assert False, b'subset cycle %s!' % possiblefilters
3411 assert False, b'subset cycle %s!' % possiblefilters
3411 allfilters.append(name)
3412 allfilters.append(name)
3412 possiblefilters.remove(name)
3413 possiblefilters.remove(name)
3413
3414
3414 # warm the cache
3415 # warm the cache
3415 if not full:
3416 if not full:
3416 for name in allfilters:
3417 for name in allfilters:
3417 repo.filtered(name).branchmap()
3418 repo.filtered(name).branchmap()
3418 if not filternames or b'unfiltered' in filternames:
3419 if not filternames or b'unfiltered' in filternames:
3419 # add unfiltered
3420 # add unfiltered
3420 allfilters.append(None)
3421 allfilters.append(None)
3421
3422
3422 if util.safehasattr(branchmap.branchcache, 'fromfile'):
3423 if util.safehasattr(branchmap.branchcache, 'fromfile'):
3423 branchcacheread = safeattrsetter(branchmap.branchcache, b'fromfile')
3424 branchcacheread = safeattrsetter(branchmap.branchcache, b'fromfile')
3424 branchcacheread.set(classmethod(lambda *args: None))
3425 branchcacheread.set(classmethod(lambda *args: None))
3425 else:
3426 else:
3426 # older versions
3427 # older versions
3427 branchcacheread = safeattrsetter(branchmap, b'read')
3428 branchcacheread = safeattrsetter(branchmap, b'read')
3428 branchcacheread.set(lambda *args: None)
3429 branchcacheread.set(lambda *args: None)
3429 branchcachewrite = safeattrsetter(branchmap.branchcache, b'write')
3430 branchcachewrite = safeattrsetter(branchmap.branchcache, b'write')
3430 branchcachewrite.set(lambda *args: None)
3431 branchcachewrite.set(lambda *args: None)
3431 try:
3432 try:
3432 for name in allfilters:
3433 for name in allfilters:
3433 printname = name
3434 printname = name
3434 if name is None:
3435 if name is None:
3435 printname = b'unfiltered'
3436 printname = b'unfiltered'
3436 timer(getbranchmap(name), title=str(printname))
3437 timer(getbranchmap(name), title=str(printname))
3437 finally:
3438 finally:
3438 branchcacheread.restore()
3439 branchcacheread.restore()
3439 branchcachewrite.restore()
3440 branchcachewrite.restore()
3440 fm.end()
3441 fm.end()
3441
3442
3442
3443
3443 @command(
3444 @command(
3444 b'perfbranchmapupdate',
3445 b'perfbranchmapupdate',
3445 [
3446 [
3446 (b'', b'base', [], b'subset of revision to start from'),
3447 (b'', b'base', [], b'subset of revision to start from'),
3447 (b'', b'target', [], b'subset of revision to end with'),
3448 (b'', b'target', [], b'subset of revision to end with'),
3448 (b'', b'clear-caches', False, b'clear cache between each runs'),
3449 (b'', b'clear-caches', False, b'clear cache between each runs'),
3449 ]
3450 ]
3450 + formatteropts,
3451 + formatteropts,
3451 )
3452 )
3452 def perfbranchmapupdate(ui, repo, base=(), target=(), **opts):
3453 def perfbranchmapupdate(ui, repo, base=(), target=(), **opts):
3453 """benchmark branchmap update from for <base> revs to <target> revs
3454 """benchmark branchmap update from for <base> revs to <target> revs
3454
3455
3455 If `--clear-caches` is passed, the following items will be reset before
3456 If `--clear-caches` is passed, the following items will be reset before
3456 each update:
3457 each update:
3457 * the changelog instance and associated indexes
3458 * the changelog instance and associated indexes
3458 * the rev-branch-cache instance
3459 * the rev-branch-cache instance
3459
3460
3460 Examples:
3461 Examples:
3461
3462
3462 # update for the one last revision
3463 # update for the one last revision
3463 $ hg perfbranchmapupdate --base 'not tip' --target 'tip'
3464 $ hg perfbranchmapupdate --base 'not tip' --target 'tip'
3464
3465
3465 $ update for change coming with a new branch
3466 $ update for change coming with a new branch
3466 $ hg perfbranchmapupdate --base 'stable' --target 'default'
3467 $ hg perfbranchmapupdate --base 'stable' --target 'default'
3467 """
3468 """
3468 from mercurial import branchmap
3469 from mercurial import branchmap
3469 from mercurial import repoview
3470 from mercurial import repoview
3470
3471
3471 opts = _byteskwargs(opts)
3472 opts = _byteskwargs(opts)
3472 timer, fm = gettimer(ui, opts)
3473 timer, fm = gettimer(ui, opts)
3473 clearcaches = opts[b'clear_caches']
3474 clearcaches = opts[b'clear_caches']
3474 unfi = repo.unfiltered()
3475 unfi = repo.unfiltered()
3475 x = [None] # used to pass data between closure
3476 x = [None] # used to pass data between closure
3476
3477
3477 # we use a `list` here to avoid possible side effect from smartset
3478 # we use a `list` here to avoid possible side effect from smartset
3478 baserevs = list(scmutil.revrange(repo, base))
3479 baserevs = list(scmutil.revrange(repo, base))
3479 targetrevs = list(scmutil.revrange(repo, target))
3480 targetrevs = list(scmutil.revrange(repo, target))
3480 if not baserevs:
3481 if not baserevs:
3481 raise error.Abort(b'no revisions selected for --base')
3482 raise error.Abort(b'no revisions selected for --base')
3482 if not targetrevs:
3483 if not targetrevs:
3483 raise error.Abort(b'no revisions selected for --target')
3484 raise error.Abort(b'no revisions selected for --target')
3484
3485
3485 # make sure the target branchmap also contains the one in the base
3486 # make sure the target branchmap also contains the one in the base
3486 targetrevs = list(set(baserevs) | set(targetrevs))
3487 targetrevs = list(set(baserevs) | set(targetrevs))
3487 targetrevs.sort()
3488 targetrevs.sort()
3488
3489
3489 cl = repo.changelog
3490 cl = repo.changelog
3490 allbaserevs = list(cl.ancestors(baserevs, inclusive=True))
3491 allbaserevs = list(cl.ancestors(baserevs, inclusive=True))
3491 allbaserevs.sort()
3492 allbaserevs.sort()
3492 alltargetrevs = frozenset(cl.ancestors(targetrevs, inclusive=True))
3493 alltargetrevs = frozenset(cl.ancestors(targetrevs, inclusive=True))
3493
3494
3494 newrevs = list(alltargetrevs.difference(allbaserevs))
3495 newrevs = list(alltargetrevs.difference(allbaserevs))
3495 newrevs.sort()
3496 newrevs.sort()
3496
3497
3497 allrevs = frozenset(unfi.changelog.revs())
3498 allrevs = frozenset(unfi.changelog.revs())
3498 basefilterrevs = frozenset(allrevs.difference(allbaserevs))
3499 basefilterrevs = frozenset(allrevs.difference(allbaserevs))
3499 targetfilterrevs = frozenset(allrevs.difference(alltargetrevs))
3500 targetfilterrevs = frozenset(allrevs.difference(alltargetrevs))
3500
3501
3501 def basefilter(repo, visibilityexceptions=None):
3502 def basefilter(repo, visibilityexceptions=None):
3502 return basefilterrevs
3503 return basefilterrevs
3503
3504
3504 def targetfilter(repo, visibilityexceptions=None):
3505 def targetfilter(repo, visibilityexceptions=None):
3505 return targetfilterrevs
3506 return targetfilterrevs
3506
3507
3507 msg = b'benchmark of branchmap with %d revisions with %d new ones\n'
3508 msg = b'benchmark of branchmap with %d revisions with %d new ones\n'
3508 ui.status(msg % (len(allbaserevs), len(newrevs)))
3509 ui.status(msg % (len(allbaserevs), len(newrevs)))
3509 if targetfilterrevs:
3510 if targetfilterrevs:
3510 msg = b'(%d revisions still filtered)\n'
3511 msg = b'(%d revisions still filtered)\n'
3511 ui.status(msg % len(targetfilterrevs))
3512 ui.status(msg % len(targetfilterrevs))
3512
3513
3513 try:
3514 try:
3514 repoview.filtertable[b'__perf_branchmap_update_base'] = basefilter
3515 repoview.filtertable[b'__perf_branchmap_update_base'] = basefilter
3515 repoview.filtertable[b'__perf_branchmap_update_target'] = targetfilter
3516 repoview.filtertable[b'__perf_branchmap_update_target'] = targetfilter
3516
3517
3517 baserepo = repo.filtered(b'__perf_branchmap_update_base')
3518 baserepo = repo.filtered(b'__perf_branchmap_update_base')
3518 targetrepo = repo.filtered(b'__perf_branchmap_update_target')
3519 targetrepo = repo.filtered(b'__perf_branchmap_update_target')
3519
3520
3520 # try to find an existing branchmap to reuse
3521 # try to find an existing branchmap to reuse
3521 subsettable = getbranchmapsubsettable()
3522 subsettable = getbranchmapsubsettable()
3522 candidatefilter = subsettable.get(None)
3523 candidatefilter = subsettable.get(None)
3523 while candidatefilter is not None:
3524 while candidatefilter is not None:
3524 candidatebm = repo.filtered(candidatefilter).branchmap()
3525 candidatebm = repo.filtered(candidatefilter).branchmap()
3525 if candidatebm.validfor(baserepo):
3526 if candidatebm.validfor(baserepo):
3526 filtered = repoview.filterrevs(repo, candidatefilter)
3527 filtered = repoview.filterrevs(repo, candidatefilter)
3527 missing = [r for r in allbaserevs if r in filtered]
3528 missing = [r for r in allbaserevs if r in filtered]
3528 base = candidatebm.copy()
3529 base = candidatebm.copy()
3529 base.update(baserepo, missing)
3530 base.update(baserepo, missing)
3530 break
3531 break
3531 candidatefilter = subsettable.get(candidatefilter)
3532 candidatefilter = subsettable.get(candidatefilter)
3532 else:
3533 else:
3533 # no suitable subset where found
3534 # no suitable subset where found
3534 base = branchmap.branchcache()
3535 base = branchmap.branchcache()
3535 base.update(baserepo, allbaserevs)
3536 base.update(baserepo, allbaserevs)
3536
3537
3537 def setup():
3538 def setup():
3538 x[0] = base.copy()
3539 x[0] = base.copy()
3539 if clearcaches:
3540 if clearcaches:
3540 unfi._revbranchcache = None
3541 unfi._revbranchcache = None
3541 clearchangelog(repo)
3542 clearchangelog(repo)
3542
3543
3543 def bench():
3544 def bench():
3544 x[0].update(targetrepo, newrevs)
3545 x[0].update(targetrepo, newrevs)
3545
3546
3546 timer(bench, setup=setup)
3547 timer(bench, setup=setup)
3547 fm.end()
3548 fm.end()
3548 finally:
3549 finally:
3549 repoview.filtertable.pop(b'__perf_branchmap_update_base', None)
3550 repoview.filtertable.pop(b'__perf_branchmap_update_base', None)
3550 repoview.filtertable.pop(b'__perf_branchmap_update_target', None)
3551 repoview.filtertable.pop(b'__perf_branchmap_update_target', None)
3551
3552
3552
3553
3553 @command(
3554 @command(
3554 b'perfbranchmapload',
3555 b'perfbranchmapload',
3555 [
3556 [
3556 (b'f', b'filter', b'', b'Specify repoview filter'),
3557 (b'f', b'filter', b'', b'Specify repoview filter'),
3557 (b'', b'list', False, b'List brachmap filter caches'),
3558 (b'', b'list', False, b'List brachmap filter caches'),
3558 (b'', b'clear-revlogs', False, b'refresh changelog and manifest'),
3559 (b'', b'clear-revlogs', False, b'refresh changelog and manifest'),
3559 ]
3560 ]
3560 + formatteropts,
3561 + formatteropts,
3561 )
3562 )
3562 def perfbranchmapload(ui, repo, filter=b'', list=False, **opts):
3563 def perfbranchmapload(ui, repo, filter=b'', list=False, **opts):
3563 """benchmark reading the branchmap"""
3564 """benchmark reading the branchmap"""
3564 opts = _byteskwargs(opts)
3565 opts = _byteskwargs(opts)
3565 clearrevlogs = opts[b'clear_revlogs']
3566 clearrevlogs = opts[b'clear_revlogs']
3566
3567
3567 if list:
3568 if list:
3568 for name, kind, st in repo.cachevfs.readdir(stat=True):
3569 for name, kind, st in repo.cachevfs.readdir(stat=True):
3569 if name.startswith(b'branch2'):
3570 if name.startswith(b'branch2'):
3570 filtername = name.partition(b'-')[2] or b'unfiltered'
3571 filtername = name.partition(b'-')[2] or b'unfiltered'
3571 ui.status(
3572 ui.status(
3572 b'%s - %s\n' % (filtername, util.bytecount(st.st_size))
3573 b'%s - %s\n' % (filtername, util.bytecount(st.st_size))
3573 )
3574 )
3574 return
3575 return
3575 if not filter:
3576 if not filter:
3576 filter = None
3577 filter = None
3577 subsettable = getbranchmapsubsettable()
3578 subsettable = getbranchmapsubsettable()
3578 if filter is None:
3579 if filter is None:
3579 repo = repo.unfiltered()
3580 repo = repo.unfiltered()
3580 else:
3581 else:
3581 repo = repoview.repoview(repo, filter)
3582 repo = repoview.repoview(repo, filter)
3582
3583
3583 repo.branchmap() # make sure we have a relevant, up to date branchmap
3584 repo.branchmap() # make sure we have a relevant, up to date branchmap
3584
3585
3585 try:
3586 try:
3586 fromfile = branchmap.branchcache.fromfile
3587 fromfile = branchmap.branchcache.fromfile
3587 except AttributeError:
3588 except AttributeError:
3588 # older versions
3589 # older versions
3589 fromfile = branchmap.read
3590 fromfile = branchmap.read
3590
3591
3591 currentfilter = filter
3592 currentfilter = filter
3592 # try once without timer, the filter may not be cached
3593 # try once without timer, the filter may not be cached
3593 while fromfile(repo) is None:
3594 while fromfile(repo) is None:
3594 currentfilter = subsettable.get(currentfilter)
3595 currentfilter = subsettable.get(currentfilter)
3595 if currentfilter is None:
3596 if currentfilter is None:
3596 raise error.Abort(
3597 raise error.Abort(
3597 b'No branchmap cached for %s repo' % (filter or b'unfiltered')
3598 b'No branchmap cached for %s repo' % (filter or b'unfiltered')
3598 )
3599 )
3599 repo = repo.filtered(currentfilter)
3600 repo = repo.filtered(currentfilter)
3600 timer, fm = gettimer(ui, opts)
3601 timer, fm = gettimer(ui, opts)
3601
3602
3602 def setup():
3603 def setup():
3603 if clearrevlogs:
3604 if clearrevlogs:
3604 clearchangelog(repo)
3605 clearchangelog(repo)
3605
3606
3606 def bench():
3607 def bench():
3607 fromfile(repo)
3608 fromfile(repo)
3608
3609
3609 timer(bench, setup=setup)
3610 timer(bench, setup=setup)
3610 fm.end()
3611 fm.end()
3611
3612
3612
3613
3613 @command(b'perfloadmarkers')
3614 @command(b'perfloadmarkers')
3614 def perfloadmarkers(ui, repo):
3615 def perfloadmarkers(ui, repo):
3615 """benchmark the time to parse the on-disk markers for a repo
3616 """benchmark the time to parse the on-disk markers for a repo
3616
3617
3617 Result is the number of markers in the repo."""
3618 Result is the number of markers in the repo."""
3618 timer, fm = gettimer(ui)
3619 timer, fm = gettimer(ui)
3619 svfs = getsvfs(repo)
3620 svfs = getsvfs(repo)
3620 timer(lambda: len(obsolete.obsstore(svfs)))
3621 timer(lambda: len(obsolete.obsstore(svfs)))
3621 fm.end()
3622 fm.end()
3622
3623
3623
3624
3624 @command(
3625 @command(
3625 b'perflrucachedict',
3626 b'perflrucachedict',
3626 formatteropts
3627 formatteropts
3627 + [
3628 + [
3628 (b'', b'costlimit', 0, b'maximum total cost of items in cache'),
3629 (b'', b'costlimit', 0, b'maximum total cost of items in cache'),
3629 (b'', b'mincost', 0, b'smallest cost of items in cache'),
3630 (b'', b'mincost', 0, b'smallest cost of items in cache'),
3630 (b'', b'maxcost', 100, b'maximum cost of items in cache'),
3631 (b'', b'maxcost', 100, b'maximum cost of items in cache'),
3631 (b'', b'size', 4, b'size of cache'),
3632 (b'', b'size', 4, b'size of cache'),
3632 (b'', b'gets', 10000, b'number of key lookups'),
3633 (b'', b'gets', 10000, b'number of key lookups'),
3633 (b'', b'sets', 10000, b'number of key sets'),
3634 (b'', b'sets', 10000, b'number of key sets'),
3634 (b'', b'mixed', 10000, b'number of mixed mode operations'),
3635 (b'', b'mixed', 10000, b'number of mixed mode operations'),
3635 (
3636 (
3636 b'',
3637 b'',
3637 b'mixedgetfreq',
3638 b'mixedgetfreq',
3638 50,
3639 50,
3639 b'frequency of get vs set ops in mixed mode',
3640 b'frequency of get vs set ops in mixed mode',
3640 ),
3641 ),
3641 ],
3642 ],
3642 norepo=True,
3643 norepo=True,
3643 )
3644 )
3644 def perflrucache(
3645 def perflrucache(
3645 ui,
3646 ui,
3646 mincost=0,
3647 mincost=0,
3647 maxcost=100,
3648 maxcost=100,
3648 costlimit=0,
3649 costlimit=0,
3649 size=4,
3650 size=4,
3650 gets=10000,
3651 gets=10000,
3651 sets=10000,
3652 sets=10000,
3652 mixed=10000,
3653 mixed=10000,
3653 mixedgetfreq=50,
3654 mixedgetfreq=50,
3654 **opts
3655 **opts
3655 ):
3656 ):
3656 opts = _byteskwargs(opts)
3657 opts = _byteskwargs(opts)
3657
3658
3658 def doinit():
3659 def doinit():
3659 for i in _xrange(10000):
3660 for i in _xrange(10000):
3660 util.lrucachedict(size)
3661 util.lrucachedict(size)
3661
3662
3662 costrange = list(range(mincost, maxcost + 1))
3663 costrange = list(range(mincost, maxcost + 1))
3663
3664
3664 values = []
3665 values = []
3665 for i in _xrange(size):
3666 for i in _xrange(size):
3666 values.append(random.randint(0, _maxint))
3667 values.append(random.randint(0, _maxint))
3667
3668
3668 # Get mode fills the cache and tests raw lookup performance with no
3669 # Get mode fills the cache and tests raw lookup performance with no
3669 # eviction.
3670 # eviction.
3670 getseq = []
3671 getseq = []
3671 for i in _xrange(gets):
3672 for i in _xrange(gets):
3672 getseq.append(random.choice(values))
3673 getseq.append(random.choice(values))
3673
3674
3674 def dogets():
3675 def dogets():
3675 d = util.lrucachedict(size)
3676 d = util.lrucachedict(size)
3676 for v in values:
3677 for v in values:
3677 d[v] = v
3678 d[v] = v
3678 for key in getseq:
3679 for key in getseq:
3679 value = d[key]
3680 value = d[key]
3680 value # silence pyflakes warning
3681 value # silence pyflakes warning
3681
3682
3682 def dogetscost():
3683 def dogetscost():
3683 d = util.lrucachedict(size, maxcost=costlimit)
3684 d = util.lrucachedict(size, maxcost=costlimit)
3684 for i, v in enumerate(values):
3685 for i, v in enumerate(values):
3685 d.insert(v, v, cost=costs[i])
3686 d.insert(v, v, cost=costs[i])
3686 for key in getseq:
3687 for key in getseq:
3687 try:
3688 try:
3688 value = d[key]
3689 value = d[key]
3689 value # silence pyflakes warning
3690 value # silence pyflakes warning
3690 except KeyError:
3691 except KeyError:
3691 pass
3692 pass
3692
3693
3693 # Set mode tests insertion speed with cache eviction.
3694 # Set mode tests insertion speed with cache eviction.
3694 setseq = []
3695 setseq = []
3695 costs = []
3696 costs = []
3696 for i in _xrange(sets):
3697 for i in _xrange(sets):
3697 setseq.append(random.randint(0, _maxint))
3698 setseq.append(random.randint(0, _maxint))
3698 costs.append(random.choice(costrange))
3699 costs.append(random.choice(costrange))
3699
3700
3700 def doinserts():
3701 def doinserts():
3701 d = util.lrucachedict(size)
3702 d = util.lrucachedict(size)
3702 for v in setseq:
3703 for v in setseq:
3703 d.insert(v, v)
3704 d.insert(v, v)
3704
3705
3705 def doinsertscost():
3706 def doinsertscost():
3706 d = util.lrucachedict(size, maxcost=costlimit)
3707 d = util.lrucachedict(size, maxcost=costlimit)
3707 for i, v in enumerate(setseq):
3708 for i, v in enumerate(setseq):
3708 d.insert(v, v, cost=costs[i])
3709 d.insert(v, v, cost=costs[i])
3709
3710
3710 def dosets():
3711 def dosets():
3711 d = util.lrucachedict(size)
3712 d = util.lrucachedict(size)
3712 for v in setseq:
3713 for v in setseq:
3713 d[v] = v
3714 d[v] = v
3714
3715
3715 # Mixed mode randomly performs gets and sets with eviction.
3716 # Mixed mode randomly performs gets and sets with eviction.
3716 mixedops = []
3717 mixedops = []
3717 for i in _xrange(mixed):
3718 for i in _xrange(mixed):
3718 r = random.randint(0, 100)
3719 r = random.randint(0, 100)
3719 if r < mixedgetfreq:
3720 if r < mixedgetfreq:
3720 op = 0
3721 op = 0
3721 else:
3722 else:
3722 op = 1
3723 op = 1
3723
3724
3724 mixedops.append(
3725 mixedops.append(
3725 (op, random.randint(0, size * 2), random.choice(costrange))
3726 (op, random.randint(0, size * 2), random.choice(costrange))
3726 )
3727 )
3727
3728
3728 def domixed():
3729 def domixed():
3729 d = util.lrucachedict(size)
3730 d = util.lrucachedict(size)
3730
3731
3731 for op, v, cost in mixedops:
3732 for op, v, cost in mixedops:
3732 if op == 0:
3733 if op == 0:
3733 try:
3734 try:
3734 d[v]
3735 d[v]
3735 except KeyError:
3736 except KeyError:
3736 pass
3737 pass
3737 else:
3738 else:
3738 d[v] = v
3739 d[v] = v
3739
3740
3740 def domixedcost():
3741 def domixedcost():
3741 d = util.lrucachedict(size, maxcost=costlimit)
3742 d = util.lrucachedict(size, maxcost=costlimit)
3742
3743
3743 for op, v, cost in mixedops:
3744 for op, v, cost in mixedops:
3744 if op == 0:
3745 if op == 0:
3745 try:
3746 try:
3746 d[v]
3747 d[v]
3747 except KeyError:
3748 except KeyError:
3748 pass
3749 pass
3749 else:
3750 else:
3750 d.insert(v, v, cost=cost)
3751 d.insert(v, v, cost=cost)
3751
3752
3752 benches = [
3753 benches = [
3753 (doinit, b'init'),
3754 (doinit, b'init'),
3754 ]
3755 ]
3755
3756
3756 if costlimit:
3757 if costlimit:
3757 benches.extend(
3758 benches.extend(
3758 [
3759 [
3759 (dogetscost, b'gets w/ cost limit'),
3760 (dogetscost, b'gets w/ cost limit'),
3760 (doinsertscost, b'inserts w/ cost limit'),
3761 (doinsertscost, b'inserts w/ cost limit'),
3761 (domixedcost, b'mixed w/ cost limit'),
3762 (domixedcost, b'mixed w/ cost limit'),
3762 ]
3763 ]
3763 )
3764 )
3764 else:
3765 else:
3765 benches.extend(
3766 benches.extend(
3766 [
3767 [
3767 (dogets, b'gets'),
3768 (dogets, b'gets'),
3768 (doinserts, b'inserts'),
3769 (doinserts, b'inserts'),
3769 (dosets, b'sets'),
3770 (dosets, b'sets'),
3770 (domixed, b'mixed'),
3771 (domixed, b'mixed'),
3771 ]
3772 ]
3772 )
3773 )
3773
3774
3774 for fn, title in benches:
3775 for fn, title in benches:
3775 timer, fm = gettimer(ui, opts)
3776 timer, fm = gettimer(ui, opts)
3776 timer(fn, title=title)
3777 timer(fn, title=title)
3777 fm.end()
3778 fm.end()
3778
3779
3779
3780
3780 @command(b'perfwrite', formatteropts)
3781 @command(b'perfwrite', formatteropts)
3781 def perfwrite(ui, repo, **opts):
3782 def perfwrite(ui, repo, **opts):
3782 """microbenchmark ui.write
3783 """microbenchmark ui.write
3783 """
3784 """
3784 opts = _byteskwargs(opts)
3785 opts = _byteskwargs(opts)
3785
3786
3786 timer, fm = gettimer(ui, opts)
3787 timer, fm = gettimer(ui, opts)
3787
3788
3788 def write():
3789 def write():
3789 for i in range(100000):
3790 for i in range(100000):
3790 ui.writenoi18n(b'Testing write performance\n')
3791 ui.writenoi18n(b'Testing write performance\n')
3791
3792
3792 timer(write)
3793 timer(write)
3793 fm.end()
3794 fm.end()
3794
3795
3795
3796
3796 def uisetup(ui):
3797 def uisetup(ui):
3797 if util.safehasattr(cmdutil, b'openrevlog') and not util.safehasattr(
3798 if util.safehasattr(cmdutil, b'openrevlog') and not util.safehasattr(
3798 commands, b'debugrevlogopts'
3799 commands, b'debugrevlogopts'
3799 ):
3800 ):
3800 # for "historical portability":
3801 # for "historical portability":
3801 # In this case, Mercurial should be 1.9 (or a79fea6b3e77) -
3802 # In this case, Mercurial should be 1.9 (or a79fea6b3e77) -
3802 # 3.7 (or 5606f7d0d063). Therefore, '--dir' option for
3803 # 3.7 (or 5606f7d0d063). Therefore, '--dir' option for
3803 # openrevlog() should cause failure, because it has been
3804 # openrevlog() should cause failure, because it has been
3804 # available since 3.5 (or 49c583ca48c4).
3805 # available since 3.5 (or 49c583ca48c4).
3805 def openrevlog(orig, repo, cmd, file_, opts):
3806 def openrevlog(orig, repo, cmd, file_, opts):
3806 if opts.get(b'dir') and not util.safehasattr(repo, b'dirlog'):
3807 if opts.get(b'dir') and not util.safehasattr(repo, b'dirlog'):
3807 raise error.Abort(
3808 raise error.Abort(
3808 b"This version doesn't support --dir option",
3809 b"This version doesn't support --dir option",
3809 hint=b"use 3.5 or later",
3810 hint=b"use 3.5 or later",
3810 )
3811 )
3811 return orig(repo, cmd, file_, opts)
3812 return orig(repo, cmd, file_, opts)
3812
3813
3813 extensions.wrapfunction(cmdutil, b'openrevlog', openrevlog)
3814 extensions.wrapfunction(cmdutil, b'openrevlog', openrevlog)
3814
3815
3815
3816
3816 @command(
3817 @command(
3817 b'perfprogress',
3818 b'perfprogress',
3818 formatteropts
3819 formatteropts
3819 + [
3820 + [
3820 (b'', b'topic', b'topic', b'topic for progress messages'),
3821 (b'', b'topic', b'topic', b'topic for progress messages'),
3821 (b'c', b'total', 1000000, b'total value we are progressing to'),
3822 (b'c', b'total', 1000000, b'total value we are progressing to'),
3822 ],
3823 ],
3823 norepo=True,
3824 norepo=True,
3824 )
3825 )
3825 def perfprogress(ui, topic=None, total=None, **opts):
3826 def perfprogress(ui, topic=None, total=None, **opts):
3826 """printing of progress bars"""
3827 """printing of progress bars"""
3827 opts = _byteskwargs(opts)
3828 opts = _byteskwargs(opts)
3828
3829
3829 timer, fm = gettimer(ui, opts)
3830 timer, fm = gettimer(ui, opts)
3830
3831
3831 def doprogress():
3832 def doprogress():
3832 with ui.makeprogress(topic, total=total) as progress:
3833 with ui.makeprogress(topic, total=total) as progress:
3833 for i in _xrange(total):
3834 for i in _xrange(total):
3834 progress.increment()
3835 progress.increment()
3835
3836
3836 timer(doprogress)
3837 timer(doprogress)
3837 fm.end()
3838 fm.end()
General Comments 0
You need to be logged in to leave comments. Login now