Debian Codegraph @

contrib/perf.py

raw
1 # perf.py - performance test routines
2 '''helper extension to measure performance
3
4 Configurations
5 ==============
6
7 ``perf``
8 --------
9
10 ``all-timing``
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
13 (default: off).
14
15 ``presleep``
16 number of second to wait before any group of runs (default: 1)
17
18 ``pre-run``
19 number of run to perform before starting measurement.
20
21 ``profile-benchmark``
22 Enable profiling for the benchmarked section.
23 (by default, the first iteration is benchmarked)
24
25 ``profiled-runs``
26 list of iteration to profile (starting from 0)
27
28 ``run-limits``
29 Control the number of runs each benchmark will perform. The option value
30 should be a list of `<time>-<numberofrun>` pairs. After each run the
31 conditions are considered in order with the following logic:
32
33 If benchmark has been running for <time> seconds, and we have performed
34 <numberofrun> iterations, stop the benchmark,
35
36 The default value is: `3.0-100, 10.0-3`
37
38 ``stub``
39 When set, benchmarks will only be run once, useful for testing
40 (default: off)
41 '''
42
43 # "historical portability" policy of perf.py:
44 #
45 # We have to do:
46 # - make perf.py "loadable" with as wide Mercurial version as possible
47 # This doesn't mean that perf commands work correctly with that Mercurial.
48 # BTW, perf.py itself has been available since 1.1 (or eb240755386d).
49 # - make historical perf command work correctly with as wide Mercurial
50 # version as possible
51 #
52 # We have to do, if possible with reasonable cost:
53 # - make recent perf command for historical feature work correctly
54 # with early Mercurial
55 #
56 # We don't have to do:
57 # - make perf command for recent feature work correctly with early
58 # Mercurial
59
60 import contextlib
61 import functools
62 import gc
63 import math
64 import os
65 import random
66 import shutil
67 import string
68 import struct
69 import sys
70 import tempfile
71 import threading
72 import time
73
74 import mercurial.revlog
75 from mercurial import (
76 changegroup,
77 cmdutil,
78 commands,
79 copies,
80 error,
81 extensions,
82 mdiff,
83 merge,
84 util,
85 )
86
87 # for "historical portability":
88 # try to import modules separately (in dict order), and ignore
89 # failure, because these aren't available with early Mercurial
90 try:
91 from mercurial import branchmap # since 2.5 (or bcee63733aad)
92 except ImportError:
93 pass
94 try:
95 from mercurial import obsolete # since 2.3 (or ad0d6c2b3279)
96 except ImportError:
97 pass
98 try:
99 from mercurial import registrar # since 3.7 (or 37d50250b696)
100
101 dir(registrar) # forcibly load it
102 except ImportError:
103 registrar = None
104 try:
105 from mercurial import repoview # since 2.5 (or 3a6ddacb7198)
106 except ImportError:
107 pass
108 try:
109 from mercurial.utils import repoviewutil # since 5.0
110 except ImportError:
111 repoviewutil = None
112 try:
113 from mercurial import scmutil # since 1.9 (or 8b252e826c68)
114 except ImportError:
115 pass
116 try:
117 from mercurial import setdiscovery # since 1.9 (or cb98fed52495)
118 except ImportError:
119 pass
120
121 try:
122 from mercurial import profiling
123 except ImportError:
124 profiling = None
125
126 try:
127 from mercurial.repo import (
128 factory as repo_factory,
129 ) # since 7.2 (or 44ea08e1193b)
130 except ImportError:
131 from mercurial import hg as repo_factory
132
133
134 try:
135 from mercurial.revlogutils import CachedDelta
136
137 btext = lambda x: x
138 except ImportError:
139 CachedDelta = tuple
140 btext = lambda x: [x]
141
142 try:
143 from mercurial.revlogutils import constants as revlog_constants
144
145 perf_rl_kind = (revlog_constants.KIND_OTHER, b'created-by-perf')
146
147 def revlog(opener, *args, **kwargs):
148 if 'target' not in kwargs:
149 kwargs['target'] = perf_rl_kind
150 return mercurial.revlog.revlog(opener, *args, **kwargs)
151
152 except (ImportError, AttributeError):
153 perf_rl_kind = None
154
155 def revlog(opener, *args, **kwargs):
156 return mercurial.revlog.revlog(opener, *args, **kwargs)
157
158
159 def identity(a):
160 return a
161
162
163 try:
164 from mercurial import pycompat
165
166 getargspec = pycompat.getargspec # added to module after 4.5
167 _byteskwargs = pycompat.byteskwargs # since 4.1 (or fbc3f73dc802)
168 _sysstr = pycompat.sysstr # since 4.0 (or 2219f4f82ede)
169 _bytestr = pycompat.bytestr # since 4.2 (or b70407bd84d5)
170 _xrange = pycompat.xrange # since 4.8 (or 7eba8f83129b)
171 fsencode = pycompat.fsencode # since 3.9 (or f4a5e0e86a7e)
172 if pycompat.ispy3:
173 _maxint = sys.maxsize # per py3 docs for replacing maxint
174 else:
175 _maxint = sys.maxint
176 except (NameError, ImportError, AttributeError):
177 import inspect
178
179 getargspec = inspect.getargspec
180 _byteskwargs = identity
181 _bytestr = str
182 fsencode = identity # no py3 support
183 _maxint = sys.maxint # no py3 support
184 _sysstr = lambda x: x # no py3 support
185 _xrange = xrange
186
187 try:
188 # 4.7+
189 queue = pycompat.queue.Queue
190 except (NameError, AttributeError, ImportError):
191 # <4.7.
192 try:
193 queue = pycompat.queue
194 except (NameError, AttributeError, ImportError):
195 import Queue as queue
196
197 try:
198 from mercurial import logcmdutil
199
200 makelogtemplater = logcmdutil.maketemplater
201 except (AttributeError, ImportError):
202 try:
203 makelogtemplater = cmdutil.makelogtemplater
204 except (AttributeError, ImportError):
205 makelogtemplater = None
206
207 # for "historical portability":
208 # define util.safehasattr forcibly, because util.safehasattr has been
209 # available since 1.9.3 (or 94b200a11cf7)
210 _undefined = object()
211
212
213 def safehasattr(thing, attr):
214 return getattr(thing, _sysstr(attr), _undefined) is not _undefined
215
216
217 setattr(util, 'safehasattr', safehasattr)
218
219 # for "historical portability":
220 # define util.timer forcibly, because util.timer has been available
221 # since ae5d60bb70c9
222 if safehasattr(time, 'perf_counter'):
223 util.timer = time.perf_counter
224 elif os.name == b'nt':
225 util.timer = time.clock
226 else:
227 util.timer = time.time
228
229 # for "historical portability":
230 # use locally defined empty option list, if formatteropts isn't
231 # available, because commands.formatteropts has been available since
232 # 3.2 (or 7a7eed5176a4), even though formatting itself has been
233 # available since 2.2 (or ae5f92e154d3)
234 formatteropts = getattr(
235 cmdutil, "formatteropts", getattr(commands, "formatteropts", [])
236 )
237
238 # for "historical portability":
239 # use locally defined option list, if debugrevlogopts isn't available,
240 # because commands.debugrevlogopts has been available since 3.7 (or
241 # 5606f7d0d063), even though cmdutil.openrevlog() has been available
242 # since 1.9 (or a79fea6b3e77).
243 revlogopts = getattr(
244 cmdutil,
245 "debugrevlogopts",
246 getattr(
247 commands,
248 "debugrevlogopts",
249 [
250 (b'c', b'changelog', False, b'open changelog'),
251 (b'm', b'manifest', False, b'open manifest'),
252 (b'', b'dir', False, b'open directory manifest'),
253 ],
254 ),
255 )
256
257 cmdtable = {}
258
259
260 # for "historical portability":
261 # define parsealiases locally, because cmdutil.parsealiases has been
262 # available since 1.5 (or 6252852b4332)
263 def parsealiases(cmd):
264 return cmd.split(b"|")
265
266
267 if safehasattr(registrar, 'command'):
268 command = registrar.command(cmdtable)
269 elif safehasattr(cmdutil, 'command'):
270 command = cmdutil.command(cmdtable)
271 if 'norepo' not in getargspec(command).args:
272 # for "historical portability":
273 # wrap original cmdutil.command, because "norepo" option has
274 # been available since 3.1 (or 75a96326cecb)
275 _command = command
276
277 def command(name, options=(), synopsis=None, norepo=False):
278 if norepo:
279 commands.norepo += b' %s' % b' '.join(parsealiases(name))
280 return _command(name, list(options), synopsis)
281
282 else:
283 # for "historical portability":
284 # define "@command" annotation locally, because cmdutil.command
285 # has been available since 1.9 (or 2daa5179e73f)
286 def command(name, options=(), synopsis=None, norepo=False):
287 def decorator(func):
288 if synopsis:
289 cmdtable[name] = func, list(options), synopsis
290 else:
291 cmdtable[name] = func, list(options)
292 if norepo:
293 commands.norepo += b' %s' % b' '.join(parsealiases(name))
294 return func
295
296 return decorator
297
298
299 try:
300 import mercurial.registrar
301 import mercurial.configitems
302
303 configtable = {}
304 configitem = mercurial.registrar.configitem(configtable)
305 configitem(
306 b'perf',
307 b'presleep',
308 default=mercurial.configitems.dynamicdefault,
309 experimental=True,
310 )
311 configitem(
312 b'perf',
313 b'stub',
314 default=mercurial.configitems.dynamicdefault,
315 experimental=True,
316 )
317 configitem(
318 b'perf',
319 b'parentscount',
320 default=mercurial.configitems.dynamicdefault,
321 experimental=True,
322 )
323 configitem(
324 b'perf',
325 b'all-timing',
326 default=mercurial.configitems.dynamicdefault,
327 experimental=True,
328 )
329 configitem(
330 b'perf',
331 b'pre-run',
332 default=mercurial.configitems.dynamicdefault,
333 )
334 configitem(
335 b'perf',
336 b'profile-benchmark',
337 default=mercurial.configitems.dynamicdefault,
338 )
339 configitem(
340 b'perf',
341 b'profiled-runs',
342 default=mercurial.configitems.dynamicdefault,
343 )
344 configitem(
345 b'perf',
346 b'run-limits',
347 default=mercurial.configitems.dynamicdefault,
348 experimental=True,
349 )
350 except (ImportError, AttributeError):
351 pass
352 except TypeError:
353 # compatibility fix for a11fd395e83f
354 # hg version: 5.2
355 configitem(
356 b'perf',
357 b'presleep',
358 default=mercurial.configitems.dynamicdefault,
359 )
360 configitem(
361 b'perf',
362 b'stub',
363 default=mercurial.configitems.dynamicdefault,
364 )
365 configitem(
366 b'perf',
367 b'parentscount',
368 default=mercurial.configitems.dynamicdefault,
369 )
370 configitem(
371 b'perf',
372 b'all-timing',
373 default=mercurial.configitems.dynamicdefault,
374 )
375 configitem(
376 b'perf',
377 b'pre-run',
378 default=mercurial.configitems.dynamicdefault,
379 )
380 configitem(
381 b'perf',
382 b'profiled-runs',
383 default=mercurial.configitems.dynamicdefault,
384 )
385 configitem(
386 b'perf',
387 b'run-limits',
388 default=mercurial.configitems.dynamicdefault,
389 )
390
391
392 def getlen(ui):
393 if ui.configbool(b"perf", b"stub", False):
394 return lambda x: 1
395 return len
396
397
398 class noop:
399 """dummy context manager"""
400
401 def __enter__(self):
402 pass
403
404 def __exit__(self, *args):
405 pass
406
407
408 NOOPCTX = noop()
409
410
411 def gettimer(ui, opts=None):
412 """return a timer function and formatter: (timer, formatter)
413
414 This function exists to gather the creation of formatter in a single
415 place instead of duplicating it in all performance commands."""
416
417 # enforce an idle period before execution to counteract power management
418 # experimental config: perf.presleep
419 time.sleep(getint(ui, b"perf", b"presleep", 1))
420
421 if opts is None:
422 opts = {}
423 # redirect all to stderr unless buffer api is in use
424 if not ui._buffers:
425 ui = ui.copy()
426 uifout = safeattrsetter(ui, b'fout', ignoremissing=True)
427 if uifout:
428 # for "historical portability":
429 # ui.fout/ferr have been available since 1.9 (or 4e1ccd4c2b6d)
430 uifout.set(ui.ferr)
431
432 # get a formatter
433 uiformatter = getattr(ui, 'formatter', None)
434 if uiformatter:
435 fm = uiformatter(b'perf', opts)
436 else:
437 # for "historical portability":
438 # define formatter locally, because ui.formatter has been
439 # available since 2.2 (or ae5f92e154d3)
440 from mercurial import node
441
442 class defaultformatter:
443 """Minimized composition of baseformatter and plainformatter"""
444
445 def __init__(self, ui, topic, opts):
446 self._ui = ui
447 if ui.debugflag:
448 self.hexfunc = node.hex
449 else:
450 self.hexfunc = node.short
451
452 def __nonzero__(self):
453 return False
454
455 __bool__ = __nonzero__
456
457 def startitem(self):
458 pass
459
460 def data(self, **data):
461 pass
462
463 def write(self, fields, deftext, *fielddata, **opts):
464 self._ui.write(deftext % fielddata, **opts)
465
466 def condwrite(self, cond, fields, deftext, *fielddata, **opts):
467 if cond:
468 self._ui.write(deftext % fielddata, **opts)
469
470 def plain(self, text, **opts):
471 self._ui.write(text, **opts)
472
473 def end(self):
474 pass
475
476 fm = defaultformatter(ui, b'perf', opts)
477
478 # stub function, runs code only once instead of in a loop
479 # experimental config: perf.stub
480 if ui.configbool(b"perf", b"stub", False):
481 return functools.partial(stub_timer, fm), fm
482
483 # experimental config: perf.all-timing
484 displayall = ui.configbool(b"perf", b"all-timing", True)
485
486 # ui.warnnoi18n was introduced in 5209fc94b982
487 ui_warn = ui.warn
488
489 # experimental config: perf.run-limits
490 limitspec = ui.configlist(b"perf", b"run-limits", [])
491 limits = []
492 for item in limitspec:
493 parts = item.split(b'-', 1)
494 if len(parts) < 2:
495 ui_warn(b'malformatted run limit entry, missing "-": %s\n' % item)
496 continue
497 try:
498 time_limit = float(_sysstr(parts[0]))
499 except ValueError as e:
500 ui_warn(
501 b'malformatted run limit entry, %s: %s\n' % (_bytestr(e), item)
502 )
503 continue
504 try:
505 run_limit = int(_sysstr(parts[1]))
506 except ValueError as e:
507 ui_warn(
508 b'malformatted run limit entry, %s: %s\n' % (_bytestr(e), item)
509 )
510 continue
511 limits.append((time_limit, run_limit))
512 if not limits:
513 limits = DEFAULTLIMITS
514
515 profiler = None
516 profiled_runs = set()
517 if profiling is not None:
518 if ui.configbool(b"perf", b"profile-benchmark", False):
519 profiler = lambda: profiling.profile(ui)
520 for run in ui.configlist(b"perf", b"profiled-runs", [0]):
521 profiled_runs.add(int(run))
522
523 prerun = getint(ui, b"perf", b"pre-run", 0)
524 t = functools.partial(
525 _timer,
526 fm,
527 displayall=displayall,
528 limits=limits,
529 prerun=prerun,
530 profiler=profiler,
531 profiled_runs=profiled_runs,
532 )
533 return t, fm
534
535
536 def stub_timer(fm, func, setup=None, title=None):
537 if setup is not None:
538 setup()
539 func()
540
541
542 @contextlib.contextmanager
543 def timeone():
544 r = []
545 ostart = os.times()
546 cstart = util.timer()
547 yield r
548 cstop = util.timer()
549 ostop = os.times()
550 a, b = ostart, ostop
551 r.append((cstop - cstart, b[0] - a[0], b[1] - a[1]))
552
553
554 # list of stop condition (elapsed time, minimal run count)
555 DEFAULTLIMITS = (
556 (3.0, 100),
557 (10.0, 3),
558 )
559
560
561 @contextlib.contextmanager
562 def noop_context():
563 yield
564
565
566 def _timer(
567 fm,
568 func,
569 setup=None,
570 context=noop_context,
571 title=None,
572 displayall=False,
573 limits=DEFAULTLIMITS,
574 prerun=0,
575 profiler=None,
576 profiled_runs=(0,),
577 ):
578 gc.collect()
579 results = []
580 count = 0
581 if profiler is None:
582 profiler = lambda: NOOPCTX
583 for i in range(prerun):
584 if setup is not None:
585 setup()
586 with context():
587 func()
588 begin = util.timer()
589 keepgoing = True
590 while keepgoing:
591 if count in profiled_runs:
592 prof = profiler()
593 else:
594 prof = NOOPCTX
595 if setup is not None:
596 setup()
597 with context():
598 gc.collect()
599 with prof:
600 with timeone() as item:
601 r = func()
602 count += 1
603 results.append(item[0])
604 cstop = util.timer()
605 # Look for a stop condition.
606 elapsed = cstop - begin
607 for t, mincount in limits:
608 if elapsed >= t and count >= mincount:
609 keepgoing = False
610 break
611
612 formatone(fm, results, title=title, result=r, displayall=displayall)
613
614
615 def formatone(fm, timings, title=None, result=None, displayall=False):
616 count = len(timings)
617
618 fm.startitem()
619
620 if title:
621 fm.write(b'title', b'! %s\n', title)
622 if result:
623 fm.write(b'result', b'! result: %s\n', result)
624
625 def display(role, entry):
626 prefix = b''
627 if role != b'best':
628 prefix = b'%s.' % role
629 fm.plain(b'!')
630 fm.write(prefix + b'wall', b' wall %f', entry[0])
631 fm.write(prefix + b'comb', b' comb %f', entry[1] + entry[2])
632 fm.write(prefix + b'user', b' user %f', entry[1])
633 fm.write(prefix + b'sys', b' sys %f', entry[2])
634 fm.write(prefix + b'count', b' (%s of %%d)' % role, count)
635 fm.plain(b'\n')
636
637 timings.sort()
638 min_val = timings[0]
639 display(b'best', min_val)
640 if displayall:
641 max_val = timings[-1]
642 display(b'max', max_val)
643 avg = tuple([sum(x) / count for x in zip(*timings)])
644 display(b'avg', avg)
645 median = timings[len(timings) // 2]
646 display(b'median', median)
647
648
649 # utilities for historical portability
650
651
652 def getint(ui, section, name, default):
653 # for "historical portability":
654 # ui.configint has been available since 1.9 (or fa2b596db182)
655 v = ui.config(section, name, None)
656 if v is None:
657 return default
658 try:
659 return int(v)
660 except ValueError:
661 raise error.ConfigError(
662 b"%s.%s is not an integer ('%s')" % (section, name, v)
663 )
664
665
666 def safeattrsetter(obj, name, ignoremissing=False):
667 """Ensure that 'obj' has 'name' attribute before subsequent setattr
668
669 This function is aborted, if 'obj' doesn't have 'name' attribute
670 at runtime. This avoids overlooking removal of an attribute, which
671 breaks assumption of performance measurement, in the future.
672
673 This function returns the object to (1) assign a new value, and
674 (2) restore an original value to the attribute.
675
676 If 'ignoremissing' is true, missing 'name' attribute doesn't cause
677 abortion, and this function returns None. This is useful to
678 examine an attribute, which isn't ensured in all Mercurial
679 versions.
680 """
681 if not util.safehasattr(obj, name):
682 if ignoremissing:
683 return None
684 raise error.Abort(
685 (
686 b"missing attribute %s of %s might break assumption"
687 b" of performance measurement"
688 )
689 % (name, obj)
690 )
691
692 origvalue = getattr(obj, _sysstr(name))
693
694 class attrutil:
695 def set(self, newvalue):
696 setattr(obj, _sysstr(name), newvalue)
697
698 def restore(self):
699 setattr(obj, _sysstr(name), origvalue)
700
701 return attrutil()
702
703
704 # utilities to examine each internal API changes
705
706
707 def getbranchmapsubsettable():
708 # for "historical portability":
709 # subsettable is defined in:
710 # - branchmap since 2.9 (or 175c6fd8cacc)
711 # - repoview since 2.5 (or 59a9f18d4587)
712 # - repoviewutil since 5.0
713 for mod in (branchmap, repoview, repoviewutil):
714 subsettable = getattr(mod, 'subsettable', None)
715 if subsettable:
716 return subsettable
717
718 # bisecting in bcee63733aad::59a9f18d4587 can reach here (both
719 # branchmap and repoview modules exist, but subsettable attribute
720 # doesn't)
721 raise error.Abort(
722 b"perfbranchmap not available with this Mercurial",
723 hint=b"use 2.5 or later",
724 )
725
726
727 def getsvfs(repo):
728 """Return appropriate object to access files under .hg/store"""
729 # for "historical portability":
730 # repo.svfs has been available since 2.3 (or 7034365089bf)
731 svfs = getattr(repo, 'svfs', None)
732 if svfs:
733 return svfs
734 else:
735 return getattr(repo, 'sopener')
736
737
738 def getvfs(repo):
739 """Return appropriate object to access files under .hg"""
740 # for "historical portability":
741 # repo.vfs has been available since 2.3 (or 7034365089bf)
742 vfs = getattr(repo, 'vfs', None)
743 if vfs:
744 return vfs
745 else:
746 return getattr(repo, 'opener')
747
748
749 def repocleartagscachefunc(repo):
750 """Return the function to clear tags cache according to repo internal API"""
751 if util.safehasattr(repo, b'_tagscache'): # since 2.0 (or 9dca7653b525)
752 # in this case, setattr(repo, '_tagscache', None) or so isn't
753 # correct way to clear tags cache, because existing code paths
754 # expect _tagscache to be a structured object.
755 def clearcache():
756 # _tagscache has been filteredpropertycache since 2.5 (or
757 # 98c867ac1330), and delattr() can't work in such case
758 if '_tagscache' in vars(repo):
759 del repo.__dict__['_tagscache']
760
761 return clearcache
762
763 repotags = safeattrsetter(repo, b'_tags', ignoremissing=True)
764 if repotags: # since 1.4 (or 5614a628d173)
765 return lambda: repotags.set(None)
766
767 repotagscache = safeattrsetter(repo, b'tagscache', ignoremissing=True)
768 if repotagscache: # since 0.6 (or d7df759d0e97)
769 return lambda: repotagscache.set(None)
770
771 # Mercurial earlier than 0.6 (or d7df759d0e97) logically reaches
772 # this point, but it isn't so problematic, because:
773 # - repo.tags of such Mercurial isn't "callable", and repo.tags()
774 # in perftags() causes failure soon
775 # - perf.py itself has been available since 1.1 (or eb240755386d)
776 raise error.Abort(b"tags API of this hg command is unknown")
777
778
779 # utilities to clear cache
780
781
782 def clearfilecache(obj, attrname):
783 unfiltered = getattr(obj, 'unfiltered', None)
784 if unfiltered is not None:
785 obj = obj.unfiltered()
786 if attrname in vars(obj):
787 delattr(obj, attrname)
788 obj._filecache.pop(attrname, None)
789
790
791 def clearchangelog(repo):
792 if repo is not repo.unfiltered():
793 object.__setattr__(repo, '_clcachekey', None)
794 object.__setattr__(repo, '_clcache', None)
795 clearfilecache(repo.unfiltered(), 'changelog')
796
797
798 # perf commands
799
800
801 @command(b'perf::walk|perfwalk', formatteropts)
802 def perfwalk(ui, repo, *pats, **opts):
803 opts = _byteskwargs(opts)
804 timer, fm = gettimer(ui, opts)
805 m = scmutil.match(repo[None], pats, {})
806 timer(
807 lambda: len(
808 list(
809 repo.dirstate.walk(m, subrepos=[], unknown=True, ignored=False)
810 )
811 )
812 )
813 fm.end()
814
815
816 @command(b'perf::annotate|perfannotate', formatteropts)
817 def perfannotate(ui, repo, f, **opts):
818 opts = _byteskwargs(opts)
819 timer, fm = gettimer(ui, opts)
820 fc = repo[b'.'][f]
821 timer(lambda: len(fc.annotate(True)))
822 fm.end()
823
824
825 @command(
826 b'perf::status|perfstatus',
827 [
828 (b'u', b'unknown', False, b'ask status to look for unknown files'),
829 (b'', b'dirstate', False, b'benchmark the internal dirstate call'),
830 ]
831 + formatteropts,
832 )
833 def perfstatus(ui, repo, **opts):
834 """benchmark the performance of a single status call
835
836 The repository data are preserved between each call.
837
838 By default, only the status of the tracked file are requested. If
839 `--unknown` is passed, the "unknown" files are also tracked.
840 """
841 opts = _byteskwargs(opts)
842 # m = match.always(repo.root, repo.getcwd())
843 # timer(lambda: sum(map(len, repo.dirstate.status(m, [], False, False,
844 # False))))
845 timer, fm = gettimer(ui, opts)
846 if opts[b'dirstate']:
847 dirstate = repo.dirstate
848 m = scmutil.matchall(repo)
849 unknown = opts[b'unknown']
850
851 def status_dirstate():
852 s = dirstate.status(
853 m, subrepos=[], ignored=False, clean=False, unknown=unknown
854 )
855 sum(map(bool, s))
856
857 if util.safehasattr(dirstate, 'running_status'):
858 with dirstate.running_status(repo):
859 timer(status_dirstate)
860 dirstate.invalidate()
861 else:
862 timer(status_dirstate)
863 else:
864 timer(lambda: sum(map(len, repo.status(unknown=opts[b'unknown']))))
865 fm.end()
866
867
868 @command(b'perf::addremove|perfaddremove', formatteropts)
869 def perfaddremove(ui, repo, **opts):
870 opts = _byteskwargs(opts)
871 timer, fm = gettimer(ui, opts)
872 try:
873 oldquiet = repo.ui.quiet
874 repo.ui.quiet = True
875 matcher = scmutil.match(repo[None])
876 opts[b'dry_run'] = True
877 if 'uipathfn' in getargspec(scmutil.addremove).args:
878 uipathfn = scmutil.getuipathfn(repo)
879 timer(lambda: scmutil.addremove(repo, matcher, b"", uipathfn, opts))
880 else:
881 timer(lambda: scmutil.addremove(repo, matcher, b"", opts))
882 finally:
883 repo.ui.quiet = oldquiet
884 fm.end()
885
886
887 def clearcaches(cl):
888 # behave somewhat consistently across internal API changes
889 if util.safehasattr(cl, b'clearcaches'):
890 cl.clearcaches()
891 elif util.safehasattr(cl, b'_nodecache'):
892 # <= hg-5.2
893 from mercurial.node import nullid, nullrev
894
895 cl._nodecache = {nullid: nullrev}
896 cl._nodepos = None
897
898
899 @command(b'perf::heads|perfheads', formatteropts)
900 def perfheads(ui, repo, **opts):
901 """benchmark the computation of a changelog heads"""
902 opts = _byteskwargs(opts)
903 timer, fm = gettimer(ui, opts)
904 cl = repo.changelog
905
906 def s():
907 clearcaches(cl)
908
909 def d():
910 len(cl.headrevs())
911
912 timer(d, setup=s)
913 fm.end()
914
915
916 def _default_clear_on_disk_tags_cache(repo):
917 from mercurial import tags
918
919 repo.cachevfs.tryunlink(tags._filename(repo))
920
921
922 def _default_clear_on_disk_tags_fnodes_cache(repo):
923 from mercurial import tags
924
925 repo.cachevfs.tryunlink(tags._fnodescachefile)
926
927
928 def _default_forget_fnodes(repo, revs):
929 """function used by the perf extension to prune some entries from the
930 fnodes cache"""
931 from mercurial import tags
932
933 missing_1 = b'\xff' * 4
934 missing_2 = b'\xff' * 20
935 cache = tags.hgtagsfnodescache(repo.unfiltered())
936 for r in revs:
937 cache._writeentry(r * tags._fnodesrecsize, missing_1, missing_2)
938 cache.write()
939
940
941 @command(
942 b'perf::tags|perftags',
943 formatteropts
944 + [
945 (b'', b'clear-revlogs', False, b'refresh changelog and manifest'),
946 (
947 b'',
948 b'clear-on-disk-cache',
949 False,
950 b'clear on disk tags cache (DESTRUCTIVE)',
951 ),
952 (
953 b'',
954 b'clear-fnode-cache-all',
955 False,
956 b'clear on disk file node cache (DESTRUCTIVE),',
957 ),
958 (
959 b'',
960 b'clear-fnode-cache-rev',
961 [],
962 b'clear on disk file node cache (DESTRUCTIVE),',
963 b'REVS',
964 ),
965 (
966 b'',
967 b'update-last',
968 b'',
969 b'simulate an update over the last N revisions (DESTRUCTIVE),',
970 b'N',
971 ),
972 ],
973 )
974 def perftags(ui, repo, **opts):
975 """Benchmark tags retrieval in various situation
976
977 The option marked as (DESTRUCTIVE) will alter the on-disk cache, possibly
978 altering performance after the command was run. However, it does not
979 destroy any stored data.
980 """
981 from mercurial import tags
982
983 opts = _byteskwargs(opts)
984 timer, fm = gettimer(ui, opts)
985 repocleartagscache = repocleartagscachefunc(repo)
986 clearrevlogs = opts[b'clear_revlogs']
987 clear_disk = opts[b'clear_on_disk_cache']
988 clear_fnode = opts[b'clear_fnode_cache_all']
989
990 clear_fnode_revs = opts[b'clear_fnode_cache_rev']
991 update_last_str = opts[b'update_last']
992 update_last = None
993 if update_last_str:
994 try:
995 update_last = int(update_last_str)
996 except ValueError:
997 msg = b'could not parse value for update-last: "%s"'
998 msg %= update_last_str
999 hint = b'value should be an integer'
1000 raise error.Abort(msg, hint=hint)
1001
1002 clear_disk_fn = getattr(
1003 tags,
1004 "clear_cache_on_disk",
1005 _default_clear_on_disk_tags_cache,
1006 )
1007 if getattr(tags, 'clear_cache_fnodes_is_working', False):
1008 clear_fnodes_fn = tags.clear_cache_fnodes
1009 else:
1010 clear_fnodes_fn = _default_clear_on_disk_tags_fnodes_cache
1011 clear_fnodes_rev_fn = getattr(
1012 tags,
1013 "forget_fnodes",
1014 _default_forget_fnodes,
1015 )
1016
1017 clear_revs = []
1018 if clear_fnode_revs:
1019 clear_revs.extend(scmutil.revrange(repo, clear_fnode_revs))
1020
1021 if update_last:
1022 revset = b'last(all(), %d)' % update_last
1023 last_revs = repo.unfiltered().revs(revset)
1024 clear_revs.extend(last_revs)
1025
1026 from mercurial import repoview
1027
1028 rev_filter = {(b'experimental', b'extra-filter-revs'): revset}
1029 with repo.ui.configoverride(rev_filter, source=b"perf"):
1030 filter_id = repoview.extrafilter(repo.ui)
1031
1032 filter_name = b'%s%%%s' % (repo.filtername, filter_id)
1033 pre_repo = repo.filtered(filter_name)
1034 pre_repo.tags() # warm the cache
1035 old_tags_path = repo.cachevfs.join(tags._filename(pre_repo))
1036 new_tags_path = repo.cachevfs.join(tags._filename(repo))
1037
1038 clear_revs = sorted(set(clear_revs))
1039
1040 def s():
1041 if update_last:
1042 util.copyfile(old_tags_path, new_tags_path)
1043 if clearrevlogs:
1044 clearchangelog(repo)
1045 clearfilecache(repo.unfiltered(), 'manifest')
1046 if clear_disk:
1047 clear_disk_fn(repo)
1048 if clear_fnode:
1049 clear_fnodes_fn(repo)
1050 elif clear_revs:
1051 clear_fnodes_rev_fn(repo, clear_revs)
1052 repocleartagscache()
1053
1054 def t():
1055 len(repo.tags())
1056
1057 timer(t, setup=s)
1058 fm.end()
1059
1060
1061 @command(b'perf::ancestors|perfancestors', formatteropts)
1062 def perfancestors(ui, repo, **opts):
1063 opts = _byteskwargs(opts)
1064 timer, fm = gettimer(ui, opts)
1065 heads = repo.changelog.headrevs()
1066
1067 def d():
1068 for a in repo.changelog.ancestors(heads):
1069 pass
1070
1071 timer(d)
1072 fm.end()
1073
1074
1075 @command(b'perf::ancestorset|perfancestorset', formatteropts)
1076 def perfancestorset(ui, repo, revset, **opts):
1077 opts = _byteskwargs(opts)
1078 timer, fm = gettimer(ui, opts)
1079 revs = repo.revs(revset)
1080 heads = repo.changelog.headrevs()
1081
1082 def d():
1083 s = repo.changelog.ancestors(heads)
1084 for rev in revs:
1085 rev in s
1086
1087 timer(d)
1088 fm.end()
1089
1090
1091 @command(
1092 b'perf::delta-find',
1093 revlogopts + formatteropts,
1094 b'-c|-m|FILE REV',
1095 )
1096 def perf_delta_find(ui, repo, arg_1, arg_2=None, **opts):
1097 """benchmark the process of finding a valid delta for a revlog revision
1098
1099 When a revlog receives a new revision (e.g. from a commit, or from an
1100 incoming bundle), it searches for a suitable delta-base to produce a delta.
1101 This perf command measures how much time we spend in this process. It
1102 operates on an already stored revision.
1103
1104 See `hg help debug-delta-find` for another related command.
1105 """
1106 from mercurial import revlogutils
1107 import mercurial.revlogutils.deltas as deltautil
1108
1109 opts = _byteskwargs(opts)
1110 if arg_2 is None:
1111 file_ = None
1112 rev = arg_1
1113 else:
1114 file_ = arg_1
1115 rev = arg_2
1116
1117 repo = repo.unfiltered()
1118
1119 timer, fm = gettimer(ui, opts)
1120
1121 rev = int(rev)
1122
1123 revlog = cmdutil.openrevlog(repo, b'perf::delta-find', file_, opts)
1124
1125 deltacomputer = deltautil.deltacomputer(revlog)
1126
1127 node = revlog.node(rev)
1128 p1r, p2r = revlog.parentrevs(rev)
1129 p1 = revlog.node(p1r)
1130 p2 = revlog.node(p2r)
1131 full_text = revlog.revision(rev)
1132 textlen = len(full_text)
1133 cachedelta = None
1134 flags = revlog.flags(rev)
1135
1136 revinfo = revlogutils.revisioninfo(
1137 node,
1138 p1,
1139 p2,
1140 btext(full_text),
1141 textlen,
1142 cachedelta,
1143 flags,
1144 )
1145
1146 # Note: we should probably purge the potential caches (like the full
1147 # manifest cache) between runs.
1148 def find_one():
1149 with revlog._datafp() as fh:
1150 deltacomputer.finddeltainfo(revinfo, fh, target_rev=rev)
1151
1152 timer(find_one)
1153 fm.end()
1154
1155
1156 @command(b'perf::discovery|perfdiscovery', formatteropts, b'PATH')
1157 def perfdiscovery(ui, repo, path, **opts):
1158 """benchmark discovery between local repo and the peer at given path"""
1159 repos = [repo, None]
1160 timer, fm = gettimer(ui, opts)
1161
1162 try:
1163 from mercurial.utils.urlutil import get_unique_pull_path_obj
1164
1165 path = get_unique_pull_path_obj(b'perfdiscovery', ui, path)
1166 except ImportError:
1167 try:
1168 from mercurial.utils.urlutil import get_unique_pull_path
1169
1170 path = get_unique_pull_path(b'perfdiscovery', repo, ui, path)[0]
1171 except ImportError:
1172 path = ui.expandpath(path)
1173
1174 def s():
1175 repos[1] = repo_factory.peer(ui, opts, path)
1176
1177 def d():
1178 setdiscovery.findcommonheads(ui, *repos)
1179
1180 timer(d, setup=s)
1181 fm.end()
1182
1183
1184 @command(
1185 b'perf::bookmarks|perfbookmarks',
1186 formatteropts
1187 + [
1188 (b'', b'clear-revlogs', False, b'refresh changelog and manifest'),
1189 ],
1190 )
1191 def perfbookmarks(ui, repo, **opts):
1192 """benchmark parsing bookmarks from disk to memory"""
1193 opts = _byteskwargs(opts)
1194 timer, fm = gettimer(ui, opts)
1195
1196 clearrevlogs = opts[b'clear_revlogs']
1197
1198 def s():
1199 if clearrevlogs:
1200 clearchangelog(repo)
1201 clearfilecache(repo, b'_bookmarks')
1202
1203 def d():
1204 repo._bookmarks
1205
1206 timer(d, setup=s)
1207 fm.end()
1208
1209
1210 @command(
1211 b'perf::bundle',
1212 [
1213 (
1214 b'r',
1215 b'rev',
1216 [],
1217 b'changesets to bundle',
1218 b'REV',
1219 ),
1220 (
1221 b't',
1222 b'type',
1223 b'none',
1224 b'bundlespec to use (see `hg help bundlespec`)',
1225 b'TYPE',
1226 ),
1227 ]
1228 + formatteropts,
1229 b'REVS',
1230 )
1231 def perfbundle(ui, repo, *revs, **opts):
1232 """benchmark the creation of a bundle from a repository
1233
1234 For now, this only supports "none" compression.
1235 """
1236 try:
1237 from mercurial import bundlecaches
1238
1239 parsebundlespec = bundlecaches.parsebundlespec
1240 except ImportError:
1241 from mercurial import exchange
1242
1243 parsebundlespec = exchange.parsebundlespec
1244
1245 from mercurial import discovery
1246 from mercurial import bundle2
1247
1248 opts = _byteskwargs(opts)
1249 timer, fm = gettimer(ui, opts)
1250
1251 cl = repo.changelog
1252 revs = list(revs)
1253 revs.extend(opts.get(b'rev', ()))
1254 revs = scmutil.revrange(repo, revs)
1255 if not revs:
1256 raise error.Abort(b"not revision specified")
1257 # make it a consistent set (ie: without topological gaps)
1258 old_len = len(revs)
1259 revs = list(repo.revs(b"%ld::%ld", revs, revs))
1260 if old_len != len(revs):
1261 new_count = len(revs) - old_len
1262 msg = b"add %d new revisions to make it a consistent set\n"
1263 ui.write_err(msg % new_count)
1264
1265 targets = [cl.node(r) for r in repo.revs(b"heads(::%ld)", revs)]
1266 bases = [cl.node(r) for r in repo.revs(b"heads(::%ld - %ld)", revs, revs)]
1267 outgoing = discovery.outgoing(repo, bases, targets)
1268
1269 bundle_spec = opts.get(b'type')
1270
1271 bundle_spec = parsebundlespec(repo, bundle_spec, strict=False)
1272
1273 cgversion = bundle_spec.params.get(b"cg.version")
1274 if cgversion is None:
1275 if bundle_spec.version == b'v1':
1276 cgversion = b'01'
1277 if bundle_spec.version == b'v2':
1278 cgversion = b'02'
1279 if cgversion not in changegroup.supportedoutgoingversions(repo):
1280 err = b"repository does not support bundle version %s"
1281 raise error.Abort(err % cgversion)
1282
1283 if cgversion == b'01': # bundle1
1284 bversion = b'HG10' + bundle_spec.wirecompression
1285 bcompression = None
1286 elif cgversion in (b'02', b'03'):
1287 bversion = b'HG20'
1288 bcompression = bundle_spec.wirecompression
1289 else:
1290 err = b'perf::bundle: unexpected changegroup version %s'
1291 raise error.ProgrammingError(err % cgversion)
1292
1293 if bcompression is None:
1294 bcompression = b'UN'
1295
1296 if bcompression != b'UN':
1297 err = b'perf::bundle: compression currently unsupported: %s'
1298 raise error.ProgrammingError(err % bcompression)
1299
1300 def do_bundle():
1301 bundle2.writenewbundle(
1302 ui,
1303 repo,
1304 b'perf::bundle',
1305 os.devnull,
1306 bversion,
1307 outgoing,
1308 bundle_spec.params,
1309 )
1310
1311 timer(do_bundle)
1312 fm.end()
1313
1314
1315 @command(b'perf::bundleread|perfbundleread', formatteropts, b'BUNDLE')
1316 def perfbundleread(ui, repo, bundlepath, **opts):
1317 """Benchmark reading of bundle files.
1318
1319 This command is meant to isolate the I/O part of bundle reading as
1320 much as possible.
1321 """
1322 from mercurial import (
1323 bundle2,
1324 exchange,
1325 streamclone,
1326 )
1327
1328 opts = _byteskwargs(opts)
1329
1330 def makebench(fn):
1331 def run():
1332 with open(bundlepath, b'rb') as fh:
1333 bundle = exchange.readbundle(ui, fh, bundlepath)
1334 fn(bundle)
1335
1336 return run
1337
1338 def makereadnbytes(size):
1339 def run():
1340 with open(bundlepath, b'rb') as fh:
1341 bundle = exchange.readbundle(ui, fh, bundlepath)
1342 while bundle.read(size):
1343 pass
1344
1345 return run
1346
1347 def makestdioread(size):
1348 def run():
1349 with open(bundlepath, b'rb') as fh:
1350 while fh.read(size):
1351 pass
1352
1353 return run
1354
1355 # bundle1
1356
1357 def deltaiter(bundle):
1358 for delta in bundle.deltaiter():
1359 pass
1360
1361 def iterchunks(bundle):
1362 for chunk in bundle.getchunks():
1363 pass
1364
1365 # bundle2
1366
1367 def forwardchunks(bundle):
1368 for chunk in bundle._forwardchunks():
1369 pass
1370
1371 def iterparts(bundle):
1372 for part in bundle.iterparts():
1373 pass
1374
1375 def iterpartsseekable(bundle):
1376 for part in bundle.iterparts(seekable=True):
1377 pass
1378
1379 def seek(bundle):
1380 for part in bundle.iterparts(seekable=True):
1381 part.seek(0, os.SEEK_END)
1382
1383 def makepartreadnbytes(size):
1384 def run():
1385 with open(bundlepath, b'rb') as fh:
1386 bundle = exchange.readbundle(ui, fh, bundlepath)
1387 for part in bundle.iterparts():
1388 while part.read(size):
1389 pass
1390
1391 return run
1392
1393 benches = [
1394 (makestdioread(8192), b'read(8k)'),
1395 (makestdioread(16384), b'read(16k)'),
1396 (makestdioread(32768), b'read(32k)'),
1397 (makestdioread(131072), b'read(128k)'),
1398 ]
1399
1400 with open(bundlepath, b'rb') as fh:
1401 bundle = exchange.readbundle(ui, fh, bundlepath)
1402
1403 if isinstance(bundle, changegroup.cg1unpacker):
1404 benches.extend(
1405 [
1406 (makebench(deltaiter), b'cg1 deltaiter()'),
1407 (makebench(iterchunks), b'cg1 getchunks()'),
1408 (makereadnbytes(8192), b'cg1 read(8k)'),
1409 (makereadnbytes(16384), b'cg1 read(16k)'),
1410 (makereadnbytes(32768), b'cg1 read(32k)'),
1411 (makereadnbytes(131072), b'cg1 read(128k)'),
1412 ]
1413 )
1414 elif isinstance(bundle, bundle2.unbundle20):
1415 benches.extend(
1416 [
1417 (makebench(forwardchunks), b'bundle2 forwardchunks()'),
1418 (makebench(iterparts), b'bundle2 iterparts()'),
1419 (
1420 makebench(iterpartsseekable),
1421 b'bundle2 iterparts() seekable',
1422 ),
1423 (makebench(seek), b'bundle2 part seek()'),
1424 (makepartreadnbytes(8192), b'bundle2 part read(8k)'),
1425 (makepartreadnbytes(16384), b'bundle2 part read(16k)'),
1426 (makepartreadnbytes(32768), b'bundle2 part read(32k)'),
1427 (makepartreadnbytes(131072), b'bundle2 part read(128k)'),
1428 ]
1429 )
1430 elif isinstance(bundle, streamclone.streamcloneapplier):
1431 raise error.Abort(b'stream clone bundles not supported')
1432 else:
1433 raise error.Abort(b'unhandled bundle type: %s' % type(bundle))
1434
1435 for fn, title in benches:
1436 timer, fm = gettimer(ui, opts)
1437 timer(fn, title=title)
1438 fm.end()
1439
1440
1441 @command(
1442 b'perf::changegroupchangelog|perfchangegroupchangelog',
1443 formatteropts
1444 + [
1445 (b'', b'cgversion', b'02', b'changegroup version'),
1446 (b'r', b'rev', b'', b'revisions to add to changegroup'),
1447 ],
1448 )
1449 def perfchangegroupchangelog(ui, repo, cgversion=b'02', rev=None, **opts):
1450 """Benchmark producing a changelog group for a changegroup.
1451
1452 This measures the time spent processing the changelog during a
1453 bundle operation. This occurs during `hg bundle` and on a server
1454 processing a `getbundle` wire protocol request (handles clones
1455 and pull requests).
1456
1457 By default, all revisions are added to the changegroup.
1458 """
1459 opts = _byteskwargs(opts)
1460 cl = repo.changelog
1461 nodes = [cl.lookup(r) for r in repo.revs(rev or b'all()')]
1462 bundler = changegroup.getbundler(cgversion, repo)
1463
1464 def d():
1465 state, chunks = bundler._generatechangelog(cl, nodes)
1466 for chunk in chunks:
1467 pass
1468
1469 timer, fm = gettimer(ui, opts)
1470
1471 # Terminal printing can interfere with timing. So disable it.
1472 with ui.configoverride({(b'progress', b'disable'): True}):
1473 timer(d)
1474
1475 fm.end()
1476
1477
1478 @command(b'perf::dirs|perfdirs', formatteropts)
1479 def perfdirs(ui, repo, **opts):
1480 opts = _byteskwargs(opts)
1481 timer, fm = gettimer(ui, opts)
1482 dirstate = repo.dirstate
1483 b'a' in dirstate
1484
1485 def d():
1486 dirstate.hasdir(b'a')
1487 try:
1488 del dirstate._map._dirs
1489 except AttributeError:
1490 pass
1491
1492 timer(d)
1493 fm.end()
1494
1495
1496 @command(
1497 b'perf::dirstate|perfdirstate',
1498 [
1499 (
1500 b'',
1501 b'iteration',
1502 None,
1503 b'benchmark a full iteration for the dirstate',
1504 ),
1505 (
1506 b'',
1507 b'contains',
1508 None,
1509 b'benchmark a large amount of `nf in dirstate` calls',
1510 ),
1511 ]
1512 + formatteropts,
1513 )
1514 def perfdirstate(ui, repo, **opts):
1515 """benchmap the time of various distate operations
1516
1517 By default benchmark the time necessary to load a dirstate from scratch.
1518 The dirstate is loaded to the point were a "contains" request can be
1519 answered.
1520 """
1521 opts = _byteskwargs(opts)
1522 timer, fm = gettimer(ui, opts)
1523 b"a" in repo.dirstate
1524
1525 if opts[b'iteration'] and opts[b'contains']:
1526 msg = b'only specify one of --iteration or --contains'
1527 raise error.Abort(msg)
1528
1529 if opts[b'iteration']:
1530 setup = None
1531 dirstate = repo.dirstate
1532
1533 def d():
1534 for f in dirstate:
1535 pass
1536
1537 elif opts[b'contains']:
1538 setup = None
1539 dirstate = repo.dirstate
1540 allfiles = list(dirstate)
1541 # also add file path that will be "missing" from the dirstate
1542 allfiles.extend([f[::-1] for f in allfiles])
1543
1544 def d():
1545 for f in allfiles:
1546 f in dirstate
1547
1548 else:
1549
1550 def setup():
1551 repo.dirstate.invalidate()
1552
1553 def d():
1554 b"a" in repo.dirstate
1555
1556 timer(d, setup=setup)
1557 fm.end()
1558
1559
1560 @command(b'perf::dirstatedirs|perfdirstatedirs', formatteropts)
1561 def perfdirstatedirs(ui, repo, **opts):
1562 """benchmap a 'dirstate.hasdir' call from an empty `dirs` cache"""
1563 opts = _byteskwargs(opts)
1564 timer, fm = gettimer(ui, opts)
1565 repo.dirstate.hasdir(b"a")
1566
1567 def setup():
1568 try:
1569 del repo.dirstate._map._dirs
1570 except AttributeError:
1571 pass
1572
1573 def d():
1574 repo.dirstate.hasdir(b"a")
1575
1576 timer(d, setup=setup)
1577 fm.end()
1578
1579
1580 @command(b'perf::dirstatefoldmap|perfdirstatefoldmap', formatteropts)
1581 def perfdirstatefoldmap(ui, repo, **opts):
1582 """benchmap a `dirstate._map.filefoldmap.get()` request
1583
1584 The dirstate filefoldmap cache is dropped between every request.
1585 """
1586 opts = _byteskwargs(opts)
1587 timer, fm = gettimer(ui, opts)
1588 dirstate = repo.dirstate
1589 dirstate._map.filefoldmap.get(b'a')
1590
1591 def setup():
1592 del dirstate._map.filefoldmap
1593
1594 def d():
1595 dirstate._map.filefoldmap.get(b'a')
1596
1597 timer(d, setup=setup)
1598 fm.end()
1599
1600
1601 @command(b'perf::dirfoldmap|perfdirfoldmap', formatteropts)
1602 def perfdirfoldmap(ui, repo, **opts):
1603 """benchmap a `dirstate._map.dirfoldmap.get()` request
1604
1605 The dirstate dirfoldmap cache is dropped between every request.
1606 """
1607 opts = _byteskwargs(opts)
1608 timer, fm = gettimer(ui, opts)
1609 dirstate = repo.dirstate
1610 dirstate._map.dirfoldmap.get(b'a')
1611
1612 def setup():
1613 del dirstate._map.dirfoldmap
1614 try:
1615 del dirstate._map._dirs
1616 except AttributeError:
1617 pass
1618
1619 def d():
1620 dirstate._map.dirfoldmap.get(b'a')
1621
1622 timer(d, setup=setup)
1623 fm.end()
1624
1625
1626 @command(b'perf::dirstatewrite|perfdirstatewrite', formatteropts)
1627 def perfdirstatewrite(ui, repo, **opts):
1628 """benchmap the time it take to write a dirstate on disk"""
1629 opts = _byteskwargs(opts)
1630 timer, fm = gettimer(ui, opts)
1631 ds = repo.dirstate
1632 b"a" in ds
1633
1634 def setup():
1635 ds._dirty = True
1636
1637 def d():
1638 ds.write(repo.currenttransaction())
1639
1640 with repo.wlock():
1641 timer(d, setup=setup)
1642 fm.end()
1643
1644
1645 def _getmergerevs(repo, opts):
1646 """parse command argument to return rev involved in merge
1647
1648 input: options dictionnary with `rev`, `from` and `bse`
1649 output: (localctx, otherctx, basectx)
1650 """
1651 if opts[b'from']:
1652 fromrev = scmutil.revsingle(repo, opts[b'from'])
1653 wctx = repo[fromrev]
1654 else:
1655 wctx = repo[None]
1656 # we don't want working dir files to be stat'd in the benchmark, so
1657 # prime that cache
1658 wctx.dirty()
1659 rctx = scmutil.revsingle(repo, opts[b'rev'], opts[b'rev'])
1660 if opts[b'base']:
1661 fromrev = scmutil.revsingle(repo, opts[b'base'])
1662 ancestor = repo[fromrev]
1663 else:
1664 ancestor = wctx.ancestor(rctx)
1665 return (wctx, rctx, ancestor)
1666
1667
1668 @command(
1669 b'perf::mergecalculate|perfmergecalculate',
1670 [
1671 (b'r', b'rev', b'.', b'rev to merge against'),
1672 (b'', b'from', b'', b'rev to merge from'),
1673 (b'', b'base', b'', b'the revision to use as base'),
1674 ]
1675 + formatteropts,
1676 )
1677 def perfmergecalculate(ui, repo, **opts):
1678 opts = _byteskwargs(opts)
1679 timer, fm = gettimer(ui, opts)
1680
1681 wctx, rctx, ancestor = _getmergerevs(repo, opts)
1682
1683 def d():
1684 # acceptremote is True because we don't want prompts in the middle of
1685 # our benchmark
1686 merge.calculateupdates(
1687 repo,
1688 wctx,
1689 rctx,
1690 [ancestor],
1691 branchmerge=False,
1692 force=False,
1693 acceptremote=True,
1694 followcopies=True,
1695 )
1696
1697 timer(d)
1698 fm.end()
1699
1700
1701 @command(
1702 b'perf::mergecopies|perfmergecopies',
1703 [
1704 (b'r', b'rev', b'.', b'rev to merge against'),
1705 (b'', b'from', b'', b'rev to merge from'),
1706 (b'', b'base', b'', b'the revision to use as base'),
1707 ]
1708 + formatteropts,
1709 )
1710 def perfmergecopies(ui, repo, **opts):
1711 """measure runtime of `copies.mergecopies`"""
1712 opts = _byteskwargs(opts)
1713 timer, fm = gettimer(ui, opts)
1714 wctx, rctx, ancestor = _getmergerevs(repo, opts)
1715
1716 def d():
1717 # acceptremote is True because we don't want prompts in the middle of
1718 # our benchmark
1719 copies.mergecopies(repo, wctx, rctx, ancestor)
1720
1721 timer(d)
1722 fm.end()
1723
1724
1725 @command(b'perf::pathcopies|perfpathcopies', [], b"REV REV")
1726 def perfpathcopies(ui, repo, rev1, rev2, **opts):
1727 """benchmark the copy tracing logic"""
1728 opts = _byteskwargs(opts)
1729 timer, fm = gettimer(ui, opts)
1730 ctx1 = scmutil.revsingle(repo, rev1, rev1)
1731 ctx2 = scmutil.revsingle(repo, rev2, rev2)
1732
1733 def d():
1734 copies.pathcopies(ctx1, ctx2)
1735
1736 timer(d)
1737 fm.end()
1738
1739
1740 @command(
1741 b'perf::phases|perfphases',
1742 [
1743 (b'', b'full', False, b'include file reading time too'),
1744 ]
1745 + formatteropts,
1746 b"",
1747 )
1748 def perfphases(ui, repo, **opts):
1749 """benchmark phasesets computation"""
1750 opts = _byteskwargs(opts)
1751 timer, fm = gettimer(ui, opts)
1752 _phases = repo._phasecache
1753 full = opts.get(b'full')
1754 tip_rev = repo.changelog.tiprev()
1755
1756 def d():
1757 phases = _phases
1758 if full:
1759 clearfilecache(repo, b'_phasecache')
1760 phases = repo._phasecache
1761 phases.invalidate()
1762 phases.phase(repo, tip_rev)
1763
1764 timer(d)
1765 fm.end()
1766
1767
1768 @command(b'perf::phasesremote|perfphasesremote', [], b"[DEST]")
1769 def perfphasesremote(ui, repo, dest=None, **opts):
1770 """benchmark time needed to analyse phases of the remote server"""
1771 from mercurial.node import bin
1772 from mercurial import (
1773 exchange,
1774 phases,
1775 )
1776
1777 opts = _byteskwargs(opts)
1778 timer, fm = gettimer(ui, opts)
1779
1780 path = ui.getpath(dest, default=(b'default-push', b'default'))
1781 if not path:
1782 raise error.Abort(
1783 b'default repository not configured!',
1784 hint=b"see 'hg help config.paths'",
1785 )
1786 if util.safehasattr(path, 'main_path'):
1787 path = path.get_push_variant()
1788 dest = path.loc
1789 else:
1790 dest = path.pushloc or path.loc
1791 ui.statusnoi18n(b'analysing phase of %s\n' % util.hidepassword(dest))
1792 other = repo_factory.peer(repo, opts, dest)
1793
1794 # easier to perform discovery through the operation
1795 op = exchange.pushoperation(repo, other)
1796 exchange._pushdiscoverychangeset(op)
1797
1798 remotesubset = op.fallbackheads
1799
1800 with other.commandexecutor() as e:
1801 remotephases = e.callcommand(
1802 b'listkeys', {b'namespace': b'phases'}
1803 ).result()
1804 del other
1805 publishing = remotephases.get(b'publishing', False)
1806 if publishing:
1807 ui.statusnoi18n(b'publishing: yes\n')
1808 else:
1809 ui.statusnoi18n(b'publishing: no\n')
1810
1811 has_node = getattr(repo.changelog.index, 'has_node', None)
1812 if has_node is None:
1813 has_node = repo.changelog.nodemap.__contains__
1814 nonpublishroots = 0
1815 for nhex, phase in remotephases.iteritems():
1816 if nhex == b'publishing': # ignore data related to publish option
1817 continue
1818 node = bin(nhex)
1819 if has_node(node) and int(phase):
1820 nonpublishroots += 1
1821 ui.statusnoi18n(b'number of roots: %d\n' % len(remotephases))
1822 ui.statusnoi18n(b'number of known non public roots: %d\n' % nonpublishroots)
1823
1824 def d():
1825 phases.remotephasessummary(repo, remotesubset, remotephases)
1826
1827 timer(d)
1828 fm.end()
1829
1830
1831 @command(
1832 b'perf::manifest|perfmanifest',
1833 [
1834 (b'm', b'manifest-rev', False, b'Look up a manifest node revision'),
1835 (b'', b'clear-disk', False, b'clear on-disk caches too'),
1836 ]
1837 + formatteropts,
1838 b'REV|NODE',
1839 )
1840 def perfmanifest(ui, repo, rev, manifest_rev=False, clear_disk=False, **opts):
1841 """benchmark the time to read a manifest from disk and return a usable
1842 dict-like object
1843
1844 Manifest caches are cleared before retrieval."""
1845 opts = _byteskwargs(opts)
1846 timer, fm = gettimer(ui, opts)
1847 if not manifest_rev:
1848 ctx = scmutil.revsingle(repo, rev, rev)
1849 t = ctx.manifestnode()
1850 else:
1851 from mercurial.node import bin
1852
1853 if len(rev) == 40:
1854 t = bin(rev)
1855 else:
1856 try:
1857 rev = int(rev)
1858
1859 if util.safehasattr(repo.manifestlog, b'getstorage'):
1860 t = repo.manifestlog.getstorage(b'').node(rev)
1861 else:
1862 t = repo.manifestlog._revlog.lookup(rev)
1863 except ValueError:
1864 raise error.Abort(
1865 b'manifest revision must be integer or full node'
1866 )
1867
1868 def d():
1869 repo.manifestlog.clearcaches(clear_persisted_data=clear_disk)
1870 repo.manifestlog[t].read()
1871
1872 timer(d)
1873 fm.end()
1874
1875
1876 @command(b'perf::changeset|perfchangeset', formatteropts)
1877 def perfchangeset(ui, repo, rev, **opts):
1878 opts = _byteskwargs(opts)
1879 timer, fm = gettimer(ui, opts)
1880 n = scmutil.revsingle(repo, rev).node()
1881
1882 def d():
1883 repo.changelog.read(n)
1884 # repo.changelog._cache = None
1885
1886 timer(d)
1887 fm.end()
1888
1889
1890 @command(b'perf::ignore|perfignore', formatteropts)
1891 def perfignore(ui, repo, **opts):
1892 """benchmark operation related to computing ignore"""
1893 opts = _byteskwargs(opts)
1894 timer, fm = gettimer(ui, opts)
1895 dirstate = repo.dirstate
1896
1897 def setupone():
1898 dirstate.invalidate()
1899 clearfilecache(dirstate, b'_ignore')
1900
1901 def runone():
1902 dirstate._ignore
1903
1904 timer(runone, setup=setupone, title=b"load")
1905 fm.end()
1906
1907
1908 @command(
1909 b'perf::index|perfindex',
1910 [
1911 (b'', b'rev', [], b'revision to be looked up (default tip)'),
1912 (b'', b'no-lookup', None, b'do not revision lookup post creation'),
1913 ]
1914 + formatteropts,
1915 )
1916 def perfindex(ui, repo, **opts):
1917 """benchmark index creation time followed by a lookup
1918
1919 The default is to look `tip` up. Depending on the index implementation,
1920 the revision looked up can matters. For example, an implementation
1921 scanning the index will have a faster lookup time for `--rev tip` than for
1922 `--rev 0`. The number of looked up revisions and their order can also
1923 matters.
1924
1925 Example of useful set to test:
1926
1927 * tip
1928 * 0
1929 * -10:
1930 * :10
1931 * -10: + :10
1932 * :10: + -10:
1933 * -10000:
1934 * -10000: + 0
1935
1936 It is not currently possible to check for lookup of a missing node. For
1937 deeper lookup benchmarking, checkout the `perfnodemap` command."""
1938 import mercurial.revlog
1939
1940 opts = _byteskwargs(opts)
1941 timer, fm = gettimer(ui, opts)
1942 mercurial.revlog._prereadsize = 2**24 # disable lazy parser in old hg
1943 if opts[b'no_lookup']:
1944 if opts['rev']:
1945 raise error.Abort('--no-lookup and --rev are mutually exclusive')
1946 nodes = []
1947 elif not opts[b'rev']:
1948 nodes = [repo[b"tip"].node()]
1949 else:
1950 revs = scmutil.revrange(repo, opts[b'rev'])
1951 cl = repo.changelog
1952 nodes = [cl.node(r) for r in revs]
1953
1954 unfi = repo.unfiltered()
1955 # find the filecache func directly
1956 # This avoid polluting the benchmark with the filecache logic
1957 makecl = unfi.__class__.changelog.func
1958
1959 def setup():
1960 # probably not necessary, but for good measure
1961 clearchangelog(unfi)
1962
1963 def d():
1964 cl = makecl(unfi)
1965 for n in nodes:
1966 cl.rev(n)
1967
1968 timer(d, setup=setup)
1969 fm.end()
1970
1971
1972 @command(
1973 b'perf::nodemap|perfnodemap',
1974 [
1975 (b'', b'rev', [], b'revision to be looked up (default tip)'),
1976 (b'', b'clear-caches', True, b'clear revlog cache between calls'),
1977 ]
1978 + formatteropts,
1979 )
1980 def perfnodemap(ui, repo, **opts):
1981 """benchmark the time necessary to look up revision from a cold nodemap
1982
1983 Depending on the implementation, the amount and order of revision we look
1984 up can varies. Example of useful set to test:
1985 * tip
1986 * 0
1987 * -10:
1988 * :10
1989 * -10: + :10
1990 * :10: + -10:
1991 * -10000:
1992 * -10000: + 0
1993
1994 The command currently focus on valid binary lookup. Benchmarking for
1995 hexlookup, prefix lookup and missing lookup would also be valuable.
1996 """
1997 import mercurial.revlog
1998
1999 opts = _byteskwargs(opts)
2000 timer, fm = gettimer(ui, opts)
2001 mercurial.revlog._prereadsize = 2**24 # disable lazy parser in old hg
2002
2003 unfi = repo.unfiltered()
2004 clearcaches = opts[b'clear_caches']
2005 # find the filecache func directly
2006 # This avoid polluting the benchmark with the filecache logic
2007 makecl = unfi.__class__.changelog.func
2008 if not opts[b'rev']:
2009 raise error.Abort(b'use --rev to specify revisions to look up')
2010 revs = scmutil.revrange(repo, opts[b'rev'])
2011 cl = repo.changelog
2012 nodes = [cl.node(r) for r in revs]
2013
2014 # use a list to pass reference to a nodemap from one closure to the next
2015 nodeget = [None]
2016
2017 def setnodeget():
2018 # probably not necessary, but for good measure
2019 clearchangelog(unfi)
2020 cl = makecl(unfi)
2021 if util.safehasattr(cl.index, 'get_rev'):
2022 nodeget[0] = cl.index.get_rev
2023 else:
2024 nodeget[0] = cl.nodemap.get
2025
2026 def d():
2027 get = nodeget[0]
2028 for n in nodes:
2029 get(n)
2030
2031 setup = None
2032 if clearcaches:
2033
2034 def setup():
2035 setnodeget()
2036
2037 else:
2038 setnodeget()
2039 d() # prewarm the data structure
2040 timer(d, setup=setup)
2041 fm.end()
2042
2043
2044 @command(b'perf::startup|perfstartup', formatteropts)
2045 def perfstartup(ui, repo, **opts):
2046 opts = _byteskwargs(opts)
2047 timer, fm = gettimer(ui, opts)
2048
2049 def d():
2050 if os.name != 'nt':
2051 os.system(
2052 b"HGRCPATH= %s version -q > /dev/null" % fsencode(sys.argv[0])
2053 )
2054 else:
2055 os.environ['HGRCPATH'] = r' '
2056 os.system("%s version -q > NUL" % sys.argv[0])
2057
2058 timer(d)
2059 fm.end()
2060
2061
2062 def _clear_store_audit_cache(repo):
2063 vfs = getsvfs(repo)
2064 # unwrap the fncache proxy
2065 if not hasattr(vfs, "audit"):
2066 vfs = getattr(vfs, "vfs", vfs)
2067 auditor = vfs.audit
2068 if hasattr(auditor, "clear_audit_cache"):
2069 auditor.clear_audit_cache()
2070 elif hasattr(auditor, "audited"):
2071 auditor.audited.clear()
2072 auditor.auditeddir.clear()
2073
2074
2075 def _find_stream_generator(version):
2076 """find the proper generator function for this stream version"""
2077 import mercurial.streamclone
2078
2079 available = {}
2080
2081 # try to fetch a v1 generator
2082 generatev1 = getattr(mercurial.streamclone, "generatev1", None)
2083 if generatev1 is not None:
2084
2085 def generate(repo):
2086 entries, bytes, data = generatev1(repo, None, None, True)
2087 return data
2088
2089 available[b'v1'] = generatev1
2090 # try to fetch a v2 generator
2091 generatev2 = getattr(mercurial.streamclone, "generatev2", None)
2092 if generatev2 is not None:
2093 post_0cdf8ccb2204 = "matcher" in getargspec(generatev2).args
2094 matcher_args = (None,) if post_0cdf8ccb2204 else (None, None)
2095
2096 def generate(repo):
2097 entries, bytes, data = generatev2(repo, *matcher_args, True)
2098 return data
2099
2100 available[b'v2'] = generate
2101 # try to fetch a v3 generator
2102 generatev3 = getattr(mercurial.streamclone, "generatev3", None)
2103 if generatev3 is not None:
2104 post_0cdf8ccb2204 = "matcher" in getargspec(generatev2).args
2105 matcher_args = (None,) if post_0cdf8ccb2204 else (None, None)
2106
2107 def generate(repo):
2108 return generatev3(repo, *matcher_args, True)
2109
2110 available[b'v3-exp'] = generate
2111
2112 # resolve the request
2113 if version == b"latest":
2114 # latest is the highest non experimental version
2115 latest_key = max(v for v in available if b'-exp' not in v)
2116 return available[latest_key]
2117 elif version in available:
2118 return available[version]
2119 else:
2120 msg = b"unkown or unavailable version: %s"
2121 msg %= version
2122 hint = b"available versions: %s"
2123 hint %= b', '.join(sorted(available))
2124 raise error.Abort(msg, hint=hint)
2125
2126
2127 @command(
2128 b'perf::stream-locked-section',
2129 [
2130 (
2131 b'',
2132 b'stream-version',
2133 b'latest',
2134 b'stream version to use ("v1", "v2", "v3-exp" '
2135 b'or "latest", (the default))',
2136 ),
2137 ]
2138 + formatteropts,
2139 )
2140 def perf_stream_clone_scan(ui, repo, stream_version, **opts):
2141 """benchmark the initial, repo-locked, section of a stream-clone"""
2142
2143 opts = _byteskwargs(opts)
2144 timer, fm = gettimer(ui, opts)
2145
2146 # deletion of the generator may trigger some cleanup that we do not want to
2147 # measure
2148 result_holder = [None]
2149
2150 def setupone():
2151 result_holder[0] = None
2152 # This is important for the full generation, even if it does not
2153 # currently matters, it seems safer to also real it here.
2154 _clear_store_audit_cache(repo)
2155
2156 generate = _find_stream_generator(stream_version)
2157
2158 def runone():
2159 # the lock is held for the duration the initialisation
2160 result_holder[0] = generate(repo)
2161
2162 timer(runone, setup=setupone, title=b"load")
2163 fm.end()
2164
2165
2166 @command(
2167 b'perf::stream-generate',
2168 [
2169 (
2170 b'',
2171 b'stream-version',
2172 b'latest',
2173 b'stream version to us ("v1", "v2", "v3-exp" '
2174 b'or "latest", (the default))',
2175 ),
2176 ]
2177 + formatteropts,
2178 )
2179 def perf_stream_clone_generate(ui, repo, stream_version, **opts):
2180 """benchmark the full generation of a stream clone"""
2181
2182 opts = _byteskwargs(opts)
2183 timer, fm = gettimer(ui, opts)
2184
2185 # deletion of the generator may trigger some cleanup that we do not want to
2186 # measure
2187
2188 generate = _find_stream_generator(stream_version)
2189
2190 def setup():
2191 _clear_store_audit_cache(repo)
2192
2193 def runone():
2194 # the lock is held for the duration the initialisation
2195 for chunk in generate(repo):
2196 pass
2197
2198 timer(runone, setup=setup, title=b"generate")
2199 fm.end()
2200
2201
2202 @command(
2203 b'perf::stream-consume',
2204 [
2205 (
2206 b'',
2207 b'in-memory-bundle',
2208 False,
2209 b'load the full bundle in userspace memory before proceeding',
2210 ),
2211 (
2212 b'',
2213 b'unbundle-progress',
2214 False,
2215 b"compute and display progress during stream processing",
2216 ),
2217 ]
2218 + formatteropts,
2219 )
2220 def perf_stream_clone_consume(ui, repo, filename, **opts):
2221 """benchmark the full application of a stream clone
2222
2223 This include the creation of the repository
2224 """
2225 # try except to appease check code
2226 msg = b"mercurial too old, missing necessary module: %s"
2227 try:
2228 from mercurial import bundle2
2229 except ImportError as exc:
2230 msg %= _bytestr(exc)
2231 raise error.Abort(msg)
2232 try:
2233 from mercurial import exchange
2234 except ImportError as exc:
2235 msg %= _bytestr(exc)
2236 raise error.Abort(msg)
2237 try:
2238 from mercurial import localrepo
2239 except ImportError as exc:
2240 msg %= _bytestr(exc)
2241 raise error.Abort(msg)
2242
2243 opts = _byteskwargs(opts)
2244 timer, fm = gettimer(ui, opts)
2245
2246 # deletion of the generator may trigger some cleanup that we do not want to
2247 # measure
2248 if not (os.path.isfile(filename) and os.access(filename, os.R_OK)):
2249 raise error.Abort("not a readable file: %s" % filename)
2250
2251 run_variables = [None, None, None]
2252
2253 # we create the new repository next to the other one for two reasons:
2254 # - this way we use the same file system, which are relevant for benchmark
2255 # - if /tmp/ is small, the operation could overfills it.
2256 source_repo_dir = os.path.dirname(repo.root)
2257
2258 @contextlib.contextmanager
2259 def context():
2260 with open(filename, mode='rb', buffering=0) as bundle:
2261 bundle_name = bundle.name
2262 if opts.get(b'in_memory_bundle'):
2263 # you hate memory, don't you?
2264 import io
2265
2266 bundle = io.BytesIO(bundle.read())
2267 with tempfile.TemporaryDirectory(
2268 prefix=b'hg-perf-stream-consume-',
2269 dir=source_repo_dir,
2270 ) as tmp_dir:
2271 tmp_dir = fsencode(tmp_dir)
2272 run_variables[0] = bundle
2273 run_variables[1] = bundle_name
2274 run_variables[2] = tmp_dir
2275 yield
2276 run_variables[0] = None
2277 run_variables[1] = None
2278 run_variables[2] = None
2279
2280 def runone():
2281 bundle = run_variables[0]
2282 bundle_name = run_variables[1]
2283 tmp_dir = run_variables[2]
2284
2285 # we actually wants to copy all config to ensure the repo config is
2286 # taken in account during the benchmark
2287 new_ui = repo.ui.__class__(repo.ui)
2288 # only pass ui when no srcrepo
2289 localrepo.createrepository(
2290 new_ui, tmp_dir, requirements=repo.requirements
2291 )
2292 target = repo_factory.repository(new_ui, tmp_dir)
2293 # we don't need to use a config override here because this is a
2294 # dedicated UI object for the disposable repository create for the
2295 # benchmark.
2296 show_progress = bool(opts.get("show_progress"))
2297 target.ui.setconfig(b"progress", b"disable", not show_progress)
2298 gen = exchange.readbundle(target.ui, bundle, bundle_name)
2299 # stream v1
2300 if util.safehasattr(gen, 'apply'):
2301 gen.apply(target)
2302 else:
2303 with target.transaction(b"perf::stream-consume") as tr:
2304 bundle2.applybundle(
2305 target,
2306 gen,
2307 tr,
2308 source=b'unbundle',
2309 url=filename,
2310 )
2311
2312 timer(runone, context=context, title=b"consume")
2313 fm.end()
2314
2315
2316 @command(b'perf::parents|perfparents', formatteropts)
2317 def perfparents(ui, repo, **opts):
2318 """benchmark the time necessary to fetch one changeset's parents.
2319
2320 The fetch is done using the `node identifier`, traversing all object layers
2321 from the repository object. The first N revisions will be used for this
2322 benchmark. N is controlled by the ``perf.parentscount`` config option
2323 (default: 1000).
2324 """
2325 opts = _byteskwargs(opts)
2326 timer, fm = gettimer(ui, opts)
2327 # control the number of commits perfparents iterates over
2328 # experimental config: perf.parentscount
2329 count = getint(ui, b"perf", b"parentscount", 1000)
2330 if len(repo.changelog) < count:
2331 raise error.Abort(b"repo needs %d commits for this test" % count)
2332 repo = repo.unfiltered()
2333 nl = [repo.changelog.node(i) for i in _xrange(count)]
2334
2335 def d():
2336 for n in nl:
2337 repo.changelog.parents(n)
2338
2339 timer(d)
2340 fm.end()
2341
2342
2343 @command(b'perf::ctxfiles|perfctxfiles', formatteropts)
2344 def perfctxfiles(ui, repo, x, **opts):
2345 opts = _byteskwargs(opts)
2346 x = int(x)
2347 timer, fm = gettimer(ui, opts)
2348
2349 def d():
2350 len(repo[x].files())
2351
2352 timer(d)
2353 fm.end()
2354
2355
2356 @command(b'perf::rawfiles|perfrawfiles', formatteropts)
2357 def perfrawfiles(ui, repo, x, **opts):
2358 opts = _byteskwargs(opts)
2359 x = int(x)
2360 timer, fm = gettimer(ui, opts)
2361 cl = repo.changelog
2362
2363 def d():
2364 len(cl.read(x)[3])
2365
2366 timer(d)
2367 fm.end()
2368
2369
2370 @command(b'perf::lookup|perflookup', formatteropts)
2371 def perflookup(ui, repo, rev, **opts):
2372 opts = _byteskwargs(opts)
2373 timer, fm = gettimer(ui, opts)
2374 timer(lambda: len(repo.lookup(rev)))
2375 fm.end()
2376
2377
2378 @command(
2379 b'perf::linelogedits|perflinelogedits',
2380 [
2381 (b'n', b'edits', 10000, b'number of edits'),
2382 (b'', b'max-hunk-lines', 10, b'max lines in a hunk'),
2383 ],
2384 norepo=True,
2385 )
2386 def perflinelogedits(ui, **opts):
2387 from mercurial import linelog
2388
2389 opts = _byteskwargs(opts)
2390
2391 edits = opts[b'edits']
2392 maxhunklines = opts[b'max_hunk_lines']
2393
2394 maxb1 = 100000
2395 random.seed(0)
2396 randint = random.randint
2397 currentlines = 0
2398 arglist = []
2399 for rev in _xrange(edits):
2400 a1 = randint(0, currentlines)
2401 a2 = randint(a1, min(currentlines, a1 + maxhunklines))
2402 b1 = randint(0, maxb1)
2403 b2 = randint(b1, b1 + maxhunklines)
2404 currentlines += (b2 - b1) - (a2 - a1)
2405 arglist.append((rev, a1, a2, b1, b2))
2406
2407 def d():
2408 ll = linelog.linelog()
2409 for args in arglist:
2410 ll.replacelines(*args)
2411
2412 timer, fm = gettimer(ui, opts)
2413 timer(d)
2414 fm.end()
2415
2416
2417 @command(b'perf::revrange|perfrevrange', formatteropts)
2418 def perfrevrange(ui, repo, *specs, **opts):
2419 opts = _byteskwargs(opts)
2420 timer, fm = gettimer(ui, opts)
2421 revrange = scmutil.revrange
2422 timer(lambda: len(revrange(repo, specs)))
2423 fm.end()
2424
2425
2426 @command(b'perf::nodelookup|perfnodelookup', formatteropts)
2427 def perfnodelookup(ui, repo, rev, **opts):
2428 opts = _byteskwargs(opts)
2429 timer, fm = gettimer(ui, opts)
2430 import mercurial.revlog
2431
2432 mercurial.revlog._prereadsize = 2**24 # disable lazy parser in old hg
2433 n = scmutil.revsingle(repo, rev).node()
2434
2435 try:
2436 cl = revlog(
2437 getsvfs(repo),
2438 radix=b"00changelog",
2439 target=(revlog_constants.KIND_CHANGELOG, None),
2440 )
2441 except TypeError:
2442 cl = revlog(getsvfs(repo), indexfile=b"00changelog.i")
2443
2444 def d():
2445 cl.rev(n)
2446 clearcaches(cl)
2447
2448 timer(d)
2449 fm.end()
2450
2451
2452 @command(
2453 b'perf::log|perflog',
2454 [(b'', b'rename', False, b'ask log to follow renames')] + formatteropts,
2455 )
2456 def perflog(ui, repo, rev=None, **opts):
2457 opts = _byteskwargs(opts)
2458 if rev is None:
2459 rev = []
2460 timer, fm = gettimer(ui, opts)
2461 ui.pushbuffer()
2462 timer(
2463 lambda: commands.log(
2464 ui, repo, rev=rev, date=b'', user=b'', copies=opts.get(b'rename')
2465 )
2466 )
2467 ui.popbuffer()
2468 fm.end()
2469
2470
2471 @command(b'perf::moonwalk|perfmoonwalk', formatteropts)
2472 def perfmoonwalk(ui, repo, **opts):
2473 """benchmark walking the changelog backwards
2474
2475 This also loads the changelog data for each revision in the changelog.
2476 """
2477 opts = _byteskwargs(opts)
2478 timer, fm = gettimer(ui, opts)
2479
2480 def moonwalk():
2481 for i in repo.changelog.revs(start=(len(repo) - 1), stop=-1):
2482 ctx = repo[i]
2483 ctx.branch() # read changelog data (in addition to the index)
2484
2485 timer(moonwalk)
2486 fm.end()
2487
2488
2489 @command(
2490 b'perf::templating|perftemplating',
2491 [
2492 (b'r', b'rev', [], b'revisions to run the template on'),
2493 ]
2494 + formatteropts,
2495 )
2496 def perftemplating(ui, repo, testedtemplate=None, **opts):
2497 """test the rendering time of a given template"""
2498 if makelogtemplater is None:
2499 raise error.Abort(
2500 b"perftemplating not available with this Mercurial",
2501 hint=b"use 4.3 or later",
2502 )
2503
2504 opts = _byteskwargs(opts)
2505
2506 nullui = ui.copy()
2507 nullui.fout = open(os.devnull, 'wb')
2508 nullui.disablepager()
2509 revs = opts.get(b'rev')
2510 if not revs:
2511 revs = [b'all()']
2512 revs = list(scmutil.revrange(repo, revs))
2513
2514 defaulttemplate = (
2515 b'{date|shortdate} [{rev}:{node|short}]'
2516 b' {author|person}: {desc|firstline}\n'
2517 )
2518 if testedtemplate is None:
2519 testedtemplate = defaulttemplate
2520 displayer = makelogtemplater(nullui, repo, testedtemplate)
2521
2522 def format():
2523 for r in revs:
2524 ctx = repo[r]
2525 displayer.show(ctx)
2526 displayer.flush(ctx)
2527
2528 timer, fm = gettimer(ui, opts)
2529 timer(format)
2530 fm.end()
2531
2532
2533 def _displaystats(ui, opts, entries, data):
2534 # use a second formatter because the data are quite different, not sure
2535 # how it flies with the templater.
2536 fm = ui.formatter(b'perf-stats', opts)
2537 for key, title in entries:
2538 values = data[key]
2539 nbvalues = len(data)
2540 values.sort()
2541 stats = {
2542 'key': key,
2543 'title': title,
2544 'nbitems': len(values),
2545 'min': values[0][0],
2546 '10%': values[(nbvalues * 10) // 100][0],
2547 '25%': values[(nbvalues * 25) // 100][0],
2548 '50%': values[(nbvalues * 50) // 100][0],
2549 '75%': values[(nbvalues * 75) // 100][0],
2550 '80%': values[(nbvalues * 80) // 100][0],
2551 '85%': values[(nbvalues * 85) // 100][0],
2552 '90%': values[(nbvalues * 90) // 100][0],
2553 '95%': values[(nbvalues * 95) // 100][0],
2554 '99%': values[(nbvalues * 99) // 100][0],
2555 'max': values[-1][0],
2556 }
2557 fm.startitem()
2558 fm.data(**stats)
2559 # make node pretty for the human output
2560 fm.plain('### %s (%d items)\n' % (title, len(values)))
2561 lines = [
2562 'min',
2563 '10%',
2564 '25%',
2565 '50%',
2566 '75%',
2567 '80%',
2568 '85%',
2569 '90%',
2570 '95%',
2571 '99%',
2572 'max',
2573 ]
2574 for l in lines:
2575 fm.plain('%s: %s\n' % (l, stats[l]))
2576 fm.end()
2577
2578
2579 @command(
2580 b'perf::helper-mergecopies|perfhelper-mergecopies',
2581 formatteropts
2582 + [
2583 (b'r', b'revs', [], b'restrict search to these revisions'),
2584 (b'', b'timing', False, b'provides extra data (costly)'),
2585 (b'', b'stats', False, b'provides statistic about the measured data'),
2586 ],
2587 )
2588 def perfhelpermergecopies(ui, repo, revs=[], **opts):
2589 """find statistics about potential parameters for `perfmergecopies`
2590
2591 This command find (base, p1, p2) triplet relevant for copytracing
2592 benchmarking in the context of a merge. It reports values for some of the
2593 parameters that impact merge copy tracing time during merge.
2594
2595 If `--timing` is set, rename detection is run and the associated timing
2596 will be reported. The extra details come at the cost of slower command
2597 execution.
2598
2599 Since rename detection is only run once, other factors might easily
2600 affect the precision of the timing. However it should give a good
2601 approximation of which revision triplets are very costly.
2602 """
2603 opts = _byteskwargs(opts)
2604 fm = ui.formatter(b'perf', opts)
2605 dotiming = opts[b'timing']
2606 dostats = opts[b'stats']
2607
2608 output_template = [
2609 ("base", "%(base)12s"),
2610 ("p1", "%(p1.node)12s"),
2611 ("p2", "%(p2.node)12s"),
2612 ("p1.nb-revs", "%(p1.nbrevs)12d"),
2613 ("p1.nb-files", "%(p1.nbmissingfiles)12d"),
2614 ("p1.renames", "%(p1.renamedfiles)12d"),
2615 ("p1.time", "%(p1.time)12.3f"),
2616 ("p2.nb-revs", "%(p2.nbrevs)12d"),
2617 ("p2.nb-files", "%(p2.nbmissingfiles)12d"),
2618 ("p2.renames", "%(p2.renamedfiles)12d"),
2619 ("p2.time", "%(p2.time)12.3f"),
2620 ("renames", "%(nbrenamedfiles)12d"),
2621 ("total.time", "%(time)12.3f"),
2622 ]
2623 if not dotiming:
2624 output_template = [
2625 i
2626 for i in output_template
2627 if not ('time' in i[0] or 'renames' in i[0])
2628 ]
2629 header_names = [h for (h, v) in output_template]
2630 output = ' '.join([v for (h, v) in output_template]) + '\n'
2631 header = ' '.join(['%12s'] * len(header_names)) + '\n'
2632 fm.plain(header % tuple(header_names))
2633
2634 if not revs:
2635 revs = ['all()']
2636 revs = scmutil.revrange(repo, revs)
2637
2638 if dostats:
2639 alldata = {
2640 'nbrevs': [],
2641 'nbmissingfiles': [],
2642 }
2643 if dotiming:
2644 alldata['parentnbrenames'] = []
2645 alldata['totalnbrenames'] = []
2646 alldata['parenttime'] = []
2647 alldata['totaltime'] = []
2648
2649 roi = repo.revs('merge() and %ld', revs)
2650 for r in roi:
2651 ctx = repo[r]
2652 p1 = ctx.p1()
2653 p2 = ctx.p2()
2654 bases = repo.changelog._commonancestorsheads(p1.rev(), p2.rev())
2655 for b in bases:
2656 b = repo[b]
2657 p1missing = copies._computeforwardmissing(b, p1)
2658 p2missing = copies._computeforwardmissing(b, p2)
2659 data = {
2660 b'base': b.hex(),
2661 b'p1.node': p1.hex(),
2662 b'p1.nbrevs': len(repo.revs('only(%d, %d)', p1.rev(), b.rev())),
2663 b'p1.nbmissingfiles': len(p1missing),
2664 b'p2.node': p2.hex(),
2665 b'p2.nbrevs': len(repo.revs('only(%d, %d)', p2.rev(), b.rev())),
2666 b'p2.nbmissingfiles': len(p2missing),
2667 }
2668 if dostats:
2669 if p1missing:
2670 alldata['nbrevs'].append(
2671 (data['p1.nbrevs'], b.hex(), p1.hex())
2672 )
2673 alldata['nbmissingfiles'].append(
2674 (data['p1.nbmissingfiles'], b.hex(), p1.hex())
2675 )
2676 if p2missing:
2677 alldata['nbrevs'].append(
2678 (data['p2.nbrevs'], b.hex(), p2.hex())
2679 )
2680 alldata['nbmissingfiles'].append(
2681 (data['p2.nbmissingfiles'], b.hex(), p2.hex())
2682 )
2683 if dotiming:
2684 begin = util.timer()
2685 mergedata = copies.mergecopies(repo, p1, p2, b)
2686 end = util.timer()
2687 # not very stable timing since we did only one run
2688 data['time'] = end - begin
2689 # mergedata contains five dicts: "copy", "movewithdir",
2690 # "diverge", "renamedelete" and "dirmove".
2691 # The first 4 are about renamed file so lets count that.
2692 renames = len(mergedata[0])
2693 renames += len(mergedata[1])
2694 renames += len(mergedata[2])
2695 renames += len(mergedata[3])
2696 data['nbrenamedfiles'] = renames
2697 begin = util.timer()
2698 p1renames = copies.pathcopies(b, p1)
2699 end = util.timer()
2700 data['p1.time'] = end - begin
2701 begin = util.timer()
2702 p2renames = copies.pathcopies(b, p2)
2703 end = util.timer()
2704 data['p2.time'] = end - begin
2705 data['p1.renamedfiles'] = len(p1renames)
2706 data['p2.renamedfiles'] = len(p2renames)
2707
2708 if dostats:
2709 if p1missing:
2710 alldata['parentnbrenames'].append(
2711 (data['p1.renamedfiles'], b.hex(), p1.hex())
2712 )
2713 alldata['parenttime'].append(
2714 (data['p1.time'], b.hex(), p1.hex())
2715 )
2716 if p2missing:
2717 alldata['parentnbrenames'].append(
2718 (data['p2.renamedfiles'], b.hex(), p2.hex())
2719 )
2720 alldata['parenttime'].append(
2721 (data['p2.time'], b.hex(), p2.hex())
2722 )
2723 if p1missing or p2missing:
2724 alldata['totalnbrenames'].append(
2725 (
2726 data['nbrenamedfiles'],
2727 b.hex(),
2728 p1.hex(),
2729 p2.hex(),
2730 )
2731 )
2732 alldata['totaltime'].append(
2733 (data['time'], b.hex(), p1.hex(), p2.hex())
2734 )
2735 fm.startitem()
2736 fm.data(**data)
2737 # make node pretty for the human output
2738 out = data.copy()
2739 out['base'] = fm.hexfunc(b.node())
2740 out['p1.node'] = fm.hexfunc(p1.node())
2741 out['p2.node'] = fm.hexfunc(p2.node())
2742 fm.plain(output % out)
2743
2744 fm.end()
2745 if dostats:
2746 # use a second formatter because the data are quite different, not sure
2747 # how it flies with the templater.
2748 entries = [
2749 ('nbrevs', 'number of revision covered'),
2750 ('nbmissingfiles', 'number of missing files at head'),
2751 ]
2752 if dotiming:
2753 entries.append(
2754 ('parentnbrenames', 'rename from one parent to base')
2755 )
2756 entries.append(('totalnbrenames', 'total number of renames'))
2757 entries.append(('parenttime', 'time for one parent'))
2758 entries.append(('totaltime', 'time for both parents'))
2759 _displaystats(ui, opts, entries, alldata)
2760
2761
2762 @command(
2763 b'perf::helper-pathcopies|perfhelper-pathcopies',
2764 formatteropts
2765 + [
2766 (b'r', b'revs', [], b'restrict search to these revisions'),
2767 (b'', b'timing', False, b'provides extra data (costly)'),
2768 (b'', b'stats', False, b'provides statistic about the measured data'),
2769 ],
2770 )
2771 def perfhelperpathcopies(ui, repo, revs=[], **opts):
2772 """find statistic about potential parameters for the `perftracecopies`
2773
2774 This command find source-destination pair relevant for copytracing testing.
2775 It report value for some of the parameters that impact copy tracing time.
2776
2777 If `--timing` is set, rename detection is run and the associated timing
2778 will be reported. The extra details comes at the cost of a slower command
2779 execution.
2780
2781 Since the rename detection is only run once, other factors might easily
2782 affect the precision of the timing. However it should give a good
2783 approximation of which revision pairs are very costly.
2784 """
2785 opts = _byteskwargs(opts)
2786 fm = ui.formatter(b'perf', opts)
2787 dotiming = opts[b'timing']
2788 dostats = opts[b'stats']
2789
2790 if dotiming:
2791 header = '%12s %12s %12s %12s %12s %12s\n'
2792 output = (
2793 "%(source)12s %(destination)12s "
2794 "%(nbrevs)12d %(nbmissingfiles)12d "
2795 "%(nbrenamedfiles)12d %(time)18.5f\n"
2796 )
2797 header_names = (
2798 "source",
2799 "destination",
2800 "nb-revs",
2801 "nb-files",
2802 "nb-renames",
2803 "time",
2804 )
2805 fm.plain(header % header_names)
2806 else:
2807 header = '%12s %12s %12s %12s\n'
2808 output = (
2809 "%(source)12s %(destination)12s "
2810 "%(nbrevs)12d %(nbmissingfiles)12d\n"
2811 )
2812 fm.plain(header % ("source", "destination", "nb-revs", "nb-files"))
2813
2814 if not revs:
2815 revs = ['all()']
2816 revs = scmutil.revrange(repo, revs)
2817
2818 if dostats:
2819 alldata = {
2820 'nbrevs': [],
2821 'nbmissingfiles': [],
2822 }
2823 if dotiming:
2824 alldata['nbrenames'] = []
2825 alldata['time'] = []
2826
2827 roi = repo.revs('merge() and %ld', revs)
2828 for r in roi:
2829 ctx = repo[r]
2830 p1 = ctx.p1().rev()
2831 p2 = ctx.p2().rev()
2832 bases = repo.changelog._commonancestorsheads(p1, p2)
2833 for p in (p1, p2):
2834 for b in bases:
2835 base = repo[b]
2836 parent = repo[p]
2837 missing = copies._computeforwardmissing(base, parent)
2838 if not missing:
2839 continue
2840 data = {
2841 b'source': base.hex(),
2842 b'destination': parent.hex(),
2843 b'nbrevs': len(repo.revs('only(%d, %d)', p, b)),
2844 b'nbmissingfiles': len(missing),
2845 }
2846 if dostats:
2847 alldata['nbrevs'].append(
2848 (
2849 data['nbrevs'],
2850 base.hex(),
2851 parent.hex(),
2852 )
2853 )
2854 alldata['nbmissingfiles'].append(
2855 (
2856 data['nbmissingfiles'],
2857 base.hex(),
2858 parent.hex(),
2859 )
2860 )
2861 if dotiming:
2862 begin = util.timer()
2863 renames = copies.pathcopies(base, parent)
2864 end = util.timer()
2865 # not very stable timing since we did only one run
2866 data['time'] = end - begin
2867 data['nbrenamedfiles'] = len(renames)
2868 if dostats:
2869 alldata['time'].append(
2870 (
2871 data['time'],
2872 base.hex(),
2873 parent.hex(),
2874 )
2875 )
2876 alldata['nbrenames'].append(
2877 (
2878 data['nbrenamedfiles'],
2879 base.hex(),
2880 parent.hex(),
2881 )
2882 )
2883 fm.startitem()
2884 fm.data(**data)
2885 out = data.copy()
2886 out['source'] = fm.hexfunc(base.node())
2887 out['destination'] = fm.hexfunc(parent.node())
2888 fm.plain(output % out)
2889
2890 fm.end()
2891 if dostats:
2892 entries = [
2893 ('nbrevs', 'number of revision covered'),
2894 ('nbmissingfiles', 'number of missing files at head'),
2895 ]
2896 if dotiming:
2897 entries.append(('nbrenames', 'renamed files'))
2898 entries.append(('time', 'time'))
2899 _displaystats(ui, opts, entries, alldata)
2900
2901
2902 @command(b'perf::cca|perfcca', formatteropts)
2903 def perfcca(ui, repo, **opts):
2904 opts = _byteskwargs(opts)
2905 timer, fm = gettimer(ui, opts)
2906 timer(lambda: scmutil.casecollisionauditor(ui, False, repo.dirstate))
2907 fm.end()
2908
2909
2910 @command(b'perf::fncacheload|perffncacheload', formatteropts)
2911 def perffncacheload(ui, repo, **opts):
2912 opts = _byteskwargs(opts)
2913 timer, fm = gettimer(ui, opts)
2914 s = repo.store
2915
2916 def d():
2917 s.fncache._load()
2918
2919 timer(d)
2920 fm.end()
2921
2922
2923 @command(b'perf::fncachewrite|perffncachewrite', formatteropts)
2924 def perffncachewrite(ui, repo, **opts):
2925 opts = _byteskwargs(opts)
2926 timer, fm = gettimer(ui, opts)
2927 s = repo.store
2928 lock = repo.lock()
2929 s.fncache._load()
2930 tr = repo.transaction(b'perffncachewrite')
2931 tr.addbackup(b'fncache')
2932
2933 def d():
2934 s.fncache._dirty = True
2935 s.fncache.write(tr)
2936
2937 timer(d)
2938 tr.close()
2939 lock.release()
2940 fm.end()
2941
2942
2943 @command(b'perf::fncacheencode|perffncacheencode', formatteropts)
2944 def perffncacheencode(ui, repo, **opts):
2945 opts = _byteskwargs(opts)
2946 timer, fm = gettimer(ui, opts)
2947 s = repo.store
2948 s.fncache._load()
2949
2950 def d():
2951 for p in s.fncache.entries:
2952 s.encode(p)
2953
2954 timer(d)
2955 fm.end()
2956
2957
2958 @command(
2959 b'perf::file-index-read',
2960 formatteropts
2961 + [
2962 (b'', b'order', b'random', b'order of paths (random, sorted, token)'),
2963 (b'', b'count', b'1', b'number (N) or percent (N%) of paths to lookup'),
2964 (b'', b'seed', 0, b'seed for --order random'),
2965 ],
2966 )
2967 def perf_file_index_read(ui, repo, **opts):
2968 """benchmark looking up paths in the file index tree"""
2969 opts = _byteskwargs(opts)
2970 timer, fm = gettimer(ui, opts)
2971 fileindex = repo.store.fileindex
2972
2973 paths = list(fileindex)
2974 order = opts[b'order']
2975 if order == b'random':
2976 random.seed(opts[b'seed'])
2977 random.shuffle(paths)
2978 elif order == b'sorted':
2979 paths.sort()
2980 elif order != b'token':
2981 raise error.CommandError(b'perf::file-index-read', b'invalid --order')
2982
2983 count = opts[b'count']
2984 if count.endswith(b'%'):
2985 # Use ceil to avoid rounding to 0.
2986 count = math.ceil(float(count[:-1]) / 100 * len(fileindex))
2987 else:
2988 count = int(count)
2989 if count < 1 or count > len(fileindex):
2990 msg = b'count %d out of range' % count
2991 raise error.CommandError(b'perf::file-index-read', msg)
2992 paths = paths[:count]
2993
2994 msg = b'looking up %d out of %d paths (%s order)\n'
2995 ui.statusnoi18n(msg % (count, len(fileindex), order))
2996
2997 def d():
2998 for path in paths:
2999 fileindex.get_token(path)
3000
3001 timer(d)
3002 fm.end()
3003
3004
3005 @command(
3006 b'perf::file-index-write',
3007 formatteropts
3008 + [
3009 (b'', b'count', 1, b'number of paths to write'),
3010 (b'', b'seed', 0, b'seed for generating random paths'),
3011 ],
3012 )
3013 def perf_file_index_write(ui, repo, **opts):
3014 """benchmark writing paths to the file index"""
3015 from mercurial.interfaces import file_index
3016
3017 opts = _byteskwargs(opts)
3018 timer, fm = gettimer(ui, opts)
3019 random.seed(opts[b'seed'])
3020
3021 with repo.lock():
3022 # Ensure we don't include vacuuming in the measurement.
3023 svfs = getsvfs(repo)
3024 svfs.options[b'fileindex-vacuum-mode'] = file_index.VacuumMode.NEVER
3025 fileindex = repo.store.fileindex
3026
3027 if len(fileindex) == 0:
3028 msg = b'benchmark requires nonempty file index'
3029 raise error.CommandError(b'perf::file-index-write', msg)
3030
3031 paths = set()
3032 paths_and_tokens = []
3033 token_count = len(fileindex) + 1
3034 ascii_letters = string.ascii_letters.encode('ascii')
3035 count = opts[b'count']
3036 for i in range(count):
3037 token = random.randrange(1, token_count)
3038 existing = fileindex.get_path(token)
3039 prefix = existing[: random.randrange(len(existing))]
3040 while True:
3041 k = random.randrange(1, 20)
3042 suffix = bytes(random.choices(ascii_letters, k=k))
3043 path = prefix + suffix
3044 if path not in fileindex and path not in paths:
3045 break
3046 paths.add(path)
3047 paths_and_tokens.append((path, token_count + i))
3048
3049 paths_str = b''.join(b'\t%s\n' % path for path, _ in paths_and_tokens)
3050 ui.notenoi18n(b'adding %d path(s):\n%s' % (count, paths_str))
3051
3052 def s():
3053 nonlocal fileindex
3054 # Reload the file index from the non-pending docket to revert the
3055 # change. The new paths will still be in the data files, but past
3056 # their "used size", so we'll overwrite the same region every time.
3057 repo.store.invalidatecaches(clearfilecache=True)
3058 fileindex = repo.store.fileindex
3059
3060 def d():
3061 for path, token in paths_and_tokens:
3062 if fileindex.add(path, tr) != token:
3063 raise error.ProgrammingError(b'unexpected token')
3064 if not tr.writepending():
3065 raise error.ProgrammingError(b'add should write')
3066
3067 tr = repo.transaction(b'perf::file-index-write')
3068 try:
3069 timer(d, setup=s)
3070 finally:
3071 tr.abort()
3072 fm.end()
3073
3074
3075 @command(b'perf::file-index-vacuum', formatteropts)
3076 def perf_file_index_vacuum(ui, repo, **opts):
3077 """benchmark vacuuming the file index tree file"""
3078 opts = _byteskwargs(opts)
3079 timer, fm = gettimer(ui, opts)
3080
3081 with repo.lock(), repo.transaction(b'perf::file-index-vacuum') as tr:
3082 fileindex = repo.store.fileindex
3083
3084 # Back up data files, otherwise the repo could be corrupted if the
3085 # command is interrupted, since we delete the initial tree file in s().
3086 for path in fileindex.data_files():
3087 tr.addbackup(path)
3088
3089 def s():
3090 # GC before each iteration so we don't accumulate lots of tree files.
3091 fileindex.garbage_collect(tr, force=True)
3092
3093 def d():
3094 # This just adds a file generator to the transaction. The actual
3095 # vacuuming happens when `writepending` runs the generator.
3096 fileindex.vacuum(tr)
3097 if not tr.writepending():
3098 raise error.ProgrammingError(b'vacuum should always write')
3099
3100 timer(d, setup=s)
3101 s() # final GC to clean up last iteration
3102 fm.end()
3103
3104
3105 def _bdiffworker(q, blocks, xdiff, ready, done):
3106 while not done.is_set():
3107 pair = q.get()
3108 while pair is not None:
3109 if xdiff:
3110 mdiff.bdiff.xdiffblocks(*pair)
3111 elif blocks:
3112 mdiff.bdiff.blocks(*pair)
3113 else:
3114 mdiff.textdiff(*pair)
3115 q.task_done()
3116 pair = q.get()
3117 q.task_done() # for the None one
3118 with ready:
3119 ready.wait()
3120
3121
3122 def _manifestrevision(repo, mnode):
3123 ml = repo.manifestlog
3124
3125 if util.safehasattr(ml, b'getstorage'):
3126 store = ml.getstorage(b'')
3127 else:
3128 store = ml._revlog
3129
3130 return store.revision(mnode)
3131
3132
3133 @command(
3134 b'perf::bdiff|perfbdiff',
3135 revlogopts
3136 + formatteropts
3137 + [
3138 (
3139 b'',
3140 b'count',
3141 1,
3142 b'number of revisions to test (when using --startrev)',
3143 ),
3144 (b'', b'alldata', False, b'test bdiffs for all associated revisions'),
3145 (b'', b'threads', 0, b'number of thread to use (disable with 0)'),
3146 (b'', b'blocks', False, b'test computing diffs into blocks'),
3147 (b'', b'xdiff', False, b'use xdiff algorithm'),
3148 ],
3149 b'-c|-m|FILE REV',
3150 )
3151 def perfbdiff(ui, repo, file_, rev=None, count=None, threads=0, **opts):
3152 """benchmark a bdiff between revisions
3153
3154 By default, benchmark a bdiff between its delta parent and itself.
3155
3156 With ``--count``, benchmark bdiffs between delta parents and self for N
3157 revisions starting at the specified revision.
3158
3159 With ``--alldata``, assume the requested revision is a changeset and
3160 measure bdiffs for all changes related to that changeset (manifest
3161 and filelogs).
3162 """
3163 opts = _byteskwargs(opts)
3164
3165 if opts[b'xdiff'] and not opts[b'blocks']:
3166 raise error.CommandError(b'perfbdiff', b'--xdiff requires --blocks')
3167
3168 if opts[b'alldata']:
3169 opts[b'changelog'] = True
3170
3171 if opts.get(b'changelog') or opts.get(b'manifest'):
3172 file_, rev = None, file_
3173 elif rev is None:
3174 raise error.CommandError(b'perfbdiff', b'invalid arguments')
3175
3176 blocks = opts[b'blocks']
3177 xdiff = opts[b'xdiff']
3178 textpairs = []
3179
3180 r = cmdutil.openrevlog(repo, b'perfbdiff', file_, opts)
3181
3182 startrev = r.rev(r.lookup(rev))
3183 for rev in range(startrev, min(startrev + count, len(r) - 1)):
3184 if opts[b'alldata']:
3185 # Load revisions associated with changeset.
3186 ctx = repo[rev]
3187 mtext = _manifestrevision(repo, ctx.manifestnode())
3188 for pctx in ctx.parents():
3189 pman = _manifestrevision(repo, pctx.manifestnode())
3190 textpairs.append((pman, mtext))
3191
3192 # Load filelog revisions by iterating manifest delta.
3193 man = ctx.manifest()
3194 pman = ctx.p1().manifest()
3195 for filename, change in pman.diff(man).items():
3196 fctx = repo.file(filename)
3197 f1 = fctx.revision(change[0][0] or -1)
3198 f2 = fctx.revision(change[1][0] or -1)
3199 textpairs.append((f1, f2))
3200 else:
3201 dp = r.deltaparent(rev)
3202 textpairs.append((r.revision(dp), r.revision(rev)))
3203
3204 withthreads = threads > 0
3205 if not withthreads:
3206
3207 def d():
3208 for pair in textpairs:
3209 if xdiff:
3210 mdiff.bdiff.xdiffblocks(*pair)
3211 elif blocks:
3212 mdiff.bdiff.blocks(*pair)
3213 else:
3214 mdiff.textdiff(*pair)
3215
3216 else:
3217 q = queue()
3218 for i in _xrange(threads):
3219 q.put(None)
3220 ready = threading.Condition()
3221 done = threading.Event()
3222 for i in _xrange(threads):
3223 threading.Thread(
3224 target=_bdiffworker, args=(q, blocks, xdiff, ready, done)
3225 ).start()
3226 q.join()
3227
3228 def d():
3229 for pair in textpairs:
3230 q.put(pair)
3231 for i in _xrange(threads):
3232 q.put(None)
3233 with ready:
3234 ready.notify_all()
3235 q.join()
3236
3237 timer, fm = gettimer(ui, opts)
3238 timer(d)
3239 fm.end()
3240
3241 if withthreads:
3242 done.set()
3243 for i in _xrange(threads):
3244 q.put(None)
3245 with ready:
3246 ready.notify_all()
3247
3248
3249 @command(
3250 b'perf::unbundle',
3251 [
3252 (b'', b'as-push', None, b'pretend the bundle comes from a push'),
3253 ]
3254 + formatteropts,
3255 b'BUNDLE_FILE',
3256 )
3257 def perf_unbundle(ui, repo, fname, **opts):
3258 """benchmark application of a bundle in a repository.
3259
3260 This does not include the final transaction processing
3261
3262 The --as-push option make the unbundle operation appears like it comes from
3263 a client push. It change some aspect of the processing and associated
3264 performance profile.
3265 """
3266
3267 from mercurial import exchange
3268 from mercurial import bundle2
3269 from mercurial import transaction
3270
3271 opts = _byteskwargs(opts)
3272
3273 ### some compatibility hotfix
3274 #
3275 # the data attribute is dropped in 63edc384d3b7 a changeset introducing a
3276 # critical regression that break transaction rollback for files that are
3277 # de-inlined.
3278 method = transaction.transaction._addentry
3279 pre_63edc384d3b7 = "data" in getargspec(method).args
3280 # the `detailed_exit_code` attribute is introduced in 33c0c25d0b0f
3281 # a changeset that is a close descendant of 18415fc918a1, the changeset
3282 # that conclude the fix run for the bug introduced in 63edc384d3b7.
3283 args = getargspec(error.Abort.__init__).args
3284 post_18415fc918a1 = "detailed_exit_code" in args
3285
3286 unbundle_source = b'perf::unbundle'
3287 if opts[b'as_push']:
3288 unbundle_source = b'push'
3289
3290 old_max_inline = None
3291 try:
3292 if not (pre_63edc384d3b7 or post_18415fc918a1):
3293 # disable inlining
3294 old_max_inline = mercurial.revlog._maxinline
3295 # large enough to never happen
3296 mercurial.revlog._maxinline = 2**50
3297
3298 with repo.lock():
3299 bundle = [None, None]
3300 orig_quiet = repo.ui.quiet
3301 try:
3302 repo.ui.quiet = True
3303 with open(fname, mode="rb") as f:
3304
3305 def noop_report(*args, **kwargs):
3306 pass
3307
3308 def setup():
3309 gen, tr = bundle
3310 if tr is not None:
3311 tr.abort()
3312 bundle[:] = [None, None]
3313 f.seek(0)
3314 bundle[0] = exchange.readbundle(ui, f, fname)
3315 bundle[1] = repo.transaction(b'perf::unbundle')
3316 # silence the transaction
3317 bundle[1]._report = noop_report
3318
3319 def apply():
3320 gen, tr = bundle
3321 bundle2.applybundle(
3322 repo,
3323 gen,
3324 tr,
3325 source=unbundle_source,
3326 url=fname,
3327 )
3328
3329 timer, fm = gettimer(ui, opts)
3330 timer(apply, setup=setup)
3331 fm.end()
3332 finally:
3333 repo.ui.quiet == orig_quiet
3334 gen, tr = bundle
3335 if tr is not None:
3336 tr.abort()
3337 finally:
3338 if old_max_inline is not None:
3339 mercurial.revlog._maxinline = old_max_inline
3340
3341
3342 @command(
3343 b'perf::unidiff|perfunidiff',
3344 revlogopts
3345 + formatteropts
3346 + [
3347 (
3348 b'',
3349 b'count',
3350 1,
3351 b'number of revisions to test (when using --startrev)',
3352 ),
3353 (b'', b'alldata', False, b'test unidiffs for all associated revisions'),
3354 ],
3355 b'-c|-m|FILE REV',
3356 )
3357 def perfunidiff(ui, repo, file_, rev=None, count=None, **opts):
3358 """benchmark a unified diff between revisions
3359
3360 This doesn't include any copy tracing - it's just a unified diff
3361 of the texts.
3362
3363 By default, benchmark a diff between its delta parent and itself.
3364
3365 With ``--count``, benchmark diffs between delta parents and self for N
3366 revisions starting at the specified revision.
3367
3368 With ``--alldata``, assume the requested revision is a changeset and
3369 measure diffs for all changes related to that changeset (manifest
3370 and filelogs).
3371 """
3372 opts = _byteskwargs(opts)
3373 if opts[b'alldata']:
3374 opts[b'changelog'] = True
3375
3376 if opts.get(b'changelog') or opts.get(b'manifest'):
3377 file_, rev = None, file_
3378 elif rev is None:
3379 raise error.CommandError(b'perfunidiff', b'invalid arguments')
3380
3381 textpairs = []
3382
3383 r = cmdutil.openrevlog(repo, b'perfunidiff', file_, opts)
3384
3385 startrev = r.rev(r.lookup(rev))
3386 for rev in range(startrev, min(startrev + count, len(r) - 1)):
3387 if opts[b'alldata']:
3388 # Load revisions associated with changeset.
3389 ctx = repo[rev]
3390 mtext = _manifestrevision(repo, ctx.manifestnode())
3391 for pctx in ctx.parents():
3392 pman = _manifestrevision(repo, pctx.manifestnode())
3393 textpairs.append((pman, mtext))
3394
3395 # Load filelog revisions by iterating manifest delta.
3396 man = ctx.manifest()
3397 pman = ctx.p1().manifest()
3398 for filename, change in pman.diff(man).items():
3399 fctx = repo.file(filename)
3400 f1 = fctx.revision(change[0][0] or -1)
3401 f2 = fctx.revision(change[1][0] or -1)
3402 textpairs.append((f1, f2))
3403 else:
3404 dp = r.deltaparent(rev)
3405 textpairs.append((r.revision(dp), r.revision(rev)))
3406
3407 def d():
3408 for left, right in textpairs:
3409 # The date strings don't matter, so we pass empty strings.
3410 headerlines, hunks = mdiff.unidiff(
3411 left, b'', right, b'', b'left', b'right', binary=False
3412 )
3413 # consume iterators in roughly the way patch.py does
3414 b'\n'.join(headerlines)
3415 b''.join(sum((list(hlines) for hrange, hlines in hunks), []))
3416
3417 timer, fm = gettimer(ui, opts)
3418 timer(d)
3419 fm.end()
3420
3421
3422 @command(b'perf::diffwd|perfdiffwd', formatteropts)
3423 def perfdiffwd(ui, repo, **opts):
3424 """Profile diff of working directory changes"""
3425 opts = _byteskwargs(opts)
3426 timer, fm = gettimer(ui, opts)
3427 options = {
3428 'w': 'ignore_all_space',
3429 'b': 'ignore_space_change',
3430 'B': 'ignore_blank_lines',
3431 }
3432
3433 for diffopt in ('', 'w', 'b', 'B', 'wB'):
3434 opts = {options[c]: b'1' for c in diffopt}
3435
3436 def d():
3437 ui.pushbuffer()
3438 commands.diff(ui, repo, **opts)
3439 ui.popbuffer()
3440
3441 diffopt = diffopt.encode('ascii')
3442 title = b'diffopts: %s' % (diffopt and (b'-' + diffopt) or b'none')
3443 timer(d, title=title)
3444 fm.end()
3445
3446
3447 @command(
3448 b'perf::revlogindex|perfrevlogindex',
3449 revlogopts + formatteropts,
3450 b'-c|-m|FILE',
3451 )
3452 def perfrevlogindex(ui, repo, file_=None, **opts):
3453 """Benchmark operations against a revlog index.
3454
3455 This tests constructing a revlog instance, reading index data,
3456 parsing index data, and performing various operations related to
3457 index data.
3458 """
3459
3460 opts = _byteskwargs(opts)
3461
3462 rl = cmdutil.openrevlog(repo, b'perfrevlogindex', file_, opts)
3463
3464 opener = getattr(rl, 'opener') # trick linter
3465 # compat with hg <= 5.8
3466 radix = getattr(rl, 'radix', None)
3467 target = getattr(rl, 'target', None)
3468 indexfile = getattr(rl, '_indexfile', None)
3469 if indexfile is None:
3470 # compatibility with <= hg-5.8
3471 indexfile = getattr(rl, 'indexfile')
3472 data = opener.read(indexfile)
3473
3474 header = struct.unpack(b'>I', data[0:4])[0]
3475 version = header & 0xFFFF
3476 if version == 1:
3477 inline = header & (1 << 16)
3478 else:
3479 raise error.Abort(b'unsupported revlog version: %d' % version)
3480
3481 parse_index_v1 = getattr(mercurial.revlog, 'parse_index_v1', None)
3482 if parse_index_v1 is None:
3483 parse_index_v1 = mercurial.revlog.revlogio().parseindex
3484
3485 uses_generaldelta = "uses_generaldelta" in getargspec(parse_index_v1).args
3486 if uses_generaldelta is not None:
3487 # Mercurial 7.0 and above
3488 # This test isn't affected by generaldelta at all, so just pass `False`
3489 parse_index_v1 = functools.partial(
3490 parse_index_v1, uses_generaldelta=False
3491 )
3492 uses_delta_info = "uses_delta_info" in getargspec(parse_index_v1).args
3493 if uses_delta_info is not None:
3494 # Mercurial 7.1 and above
3495 # This test isn't affected by delta_info at all, so just pass `False`
3496 parse_index_v1 = functools.partial(
3497 parse_index_v1,
3498 uses_delta_info=False,
3499 )
3500
3501 rllen = len(rl)
3502
3503 node0 = rl.node(0)
3504 node25 = rl.node(rllen // 4)
3505 node50 = rl.node(rllen // 2)
3506 node75 = rl.node(rllen // 4 * 3)
3507 node100 = rl.node(rllen - 1)
3508
3509 allrevs = range(rllen)
3510 allrevsrev = list(reversed(allrevs))
3511 allnodes = [rl.node(rev) for rev in range(rllen)]
3512 allnodesrev = list(reversed(allnodes))
3513
3514 def constructor():
3515 if radix is not None:
3516 revlog(opener, radix=radix, target=target)
3517 else:
3518 # hg <= 5.8
3519 revlog(opener, indexfile=indexfile)
3520
3521 def read():
3522 with opener(indexfile) as fh:
3523 fh.read()
3524
3525 def parseindex():
3526 parse_index_v1(data, inline)
3527
3528 def getentry(revornode):
3529 index = parse_index_v1(data, inline)[0]
3530 index[revornode]
3531
3532 def getentries(revs, count=1):
3533 index = parse_index_v1(data, inline)[0]
3534
3535 for i in range(count):
3536 for rev in revs:
3537 index[rev]
3538
3539 def resolvenode(node):
3540 index = parse_index_v1(data, inline)[0]
3541 rev = getattr(index, 'rev', None)
3542 if rev is None:
3543 nodemap = getattr(parse_index_v1(data, inline)[0], 'nodemap', None)
3544 # This only works for the C code.
3545 if nodemap is None:
3546 return
3547 rev = nodemap.__getitem__
3548
3549 try:
3550 rev(node)
3551 except error.RevlogError:
3552 pass
3553
3554 def resolvenodes(nodes, count=1):
3555 index = parse_index_v1(data, inline)[0]
3556 rev = getattr(index, 'rev', None)
3557 if rev is None:
3558 nodemap = getattr(parse_index_v1(data, inline)[0], 'nodemap', None)
3559 # This only works for the C code.
3560 if nodemap is None:
3561 return
3562 rev = nodemap.__getitem__
3563
3564 for i in range(count):
3565 for node in nodes:
3566 try:
3567 rev(node)
3568 except error.RevlogError:
3569 pass
3570
3571 benches = [
3572 (constructor, b'revlog constructor'),
3573 (read, b'read'),
3574 (parseindex, b'create index object'),
3575 (lambda: getentry(0), b'retrieve index entry for rev 0'),
3576 (lambda: resolvenode(b'a' * 20), b'look up missing node'),
3577 (lambda: resolvenode(node0), b'look up node at rev 0'),
3578 (lambda: resolvenode(node25), b'look up node at 1/4 len'),
3579 (lambda: resolvenode(node50), b'look up node at 1/2 len'),
3580 (lambda: resolvenode(node75), b'look up node at 3/4 len'),
3581 (lambda: resolvenode(node100), b'look up node at tip'),
3582 # 2x variation is to measure caching impact.
3583 (lambda: resolvenodes(allnodes), b'look up all nodes (forward)'),
3584 (lambda: resolvenodes(allnodes, 2), b'look up all nodes 2x (forward)'),
3585 (lambda: resolvenodes(allnodesrev), b'look up all nodes (reverse)'),
3586 (
3587 lambda: resolvenodes(allnodesrev, 2),
3588 b'look up all nodes 2x (reverse)',
3589 ),
3590 (lambda: getentries(allrevs), b'retrieve all index entries (forward)'),
3591 (
3592 lambda: getentries(allrevs, 2),
3593 b'retrieve all index entries 2x (forward)',
3594 ),
3595 (
3596 lambda: getentries(allrevsrev),
3597 b'retrieve all index entries (reverse)',
3598 ),
3599 (
3600 lambda: getentries(allrevsrev, 2),
3601 b'retrieve all index entries 2x (reverse)',
3602 ),
3603 ]
3604
3605 for fn, title in benches:
3606 timer, fm = gettimer(ui, opts)
3607 timer(fn, title=title)
3608 fm.end()
3609
3610
3611 @command(
3612 b'perf::revlog-read-revisions|perf::revlogrevisions|perfrevlogrevisions',
3613 revlogopts
3614 + formatteropts
3615 + [
3616 (b'd', b'dist', 100, b'distance between the revisions'),
3617 (b's', b'startrev', 0, b'revision to start reading at'),
3618 (b'', b'reverse', False, b'read in reverse'),
3619 (b'', b'checksum', True, b'check-integrity'),
3620 (
3621 b'',
3622 b'reuse-caches',
3623 False,
3624 b'reuse caches instead of clearing between runs',
3625 ),
3626 ],
3627 b'-c|-m|FILE',
3628 )
3629 def perfrevlogrevisions(
3630 ui,
3631 repo,
3632 file_=None,
3633 startrev=0,
3634 reverse=False,
3635 checksum=True,
3636 **opts,
3637 ):
3638 """Benchmark reading a series of revisions from a revlog.
3639
3640 By default, we read every ``-d/--dist`` revision from 0 to tip of
3641 the specified revlog.
3642
3643 The start revision can be defined via ``-s/--startrev``.
3644 """
3645 opts = _byteskwargs(opts)
3646 use_caches = opts[b'reuse_caches']
3647
3648 rl = cmdutil.openrevlog(repo, b'perfrevlogrevisions', file_, opts)
3649 rllen = getlen(ui)(rl)
3650
3651 if startrev < 0:
3652 startrev = rllen + startrev
3653
3654 def d():
3655 if not use_caches:
3656 rl.clearcaches()
3657
3658 beginrev = startrev
3659 endrev = rllen
3660 dist = opts[b'dist']
3661
3662 if reverse:
3663 beginrev, endrev = endrev - 1, beginrev - 1
3664 dist = -1 * dist
3665
3666 for x in _xrange(beginrev, endrev, dist):
3667 # Old revisions don't support passing int.
3668 n = rl.node(x)
3669 if checksum:
3670 rl.revision(n)
3671 else:
3672 rl.rawdata(n, validate=False)
3673
3674 timer, fm = gettimer(ui, opts)
3675 timer(d)
3676 fm.end()
3677
3678
3679 @command(
3680 b'perf::revlog-revdiff',
3681 revlogopts
3682 + formatteropts
3683 + [
3684 (b'', b'target', [], b'target to diff against (prev, parents)'),
3685 (
3686 b'',
3687 b'filter',
3688 [],
3689 b'restricting diffing to (storage, common-base, distinct-base)',
3690 ),
3691 (b'', b'clear-caches', False, b'clear revlog cache between calls'),
3692 ],
3693 b'-c|-m|FILE',
3694 )
3695 def perf_revlog_revdiff(
3696 ui, repo, file_=None, startrev=1000, stoprev=-1, **opts
3697 ):
3698 """check how long it take to redelta a set of revision pair"""
3699 bopts = _byteskwargs(opts)
3700 rl = cmdutil.openrevlog(repo, b'perfrevlogwrite', file_, bopts)
3701 clear_caches = bopts[b'clear_caches']
3702
3703 KNOWN_TARGET = {
3704 b'prev',
3705 b'parents',
3706 }
3707 if not bopts[b'target']:
3708 targets = KNOWN_TARGET
3709 else:
3710 targets = set()
3711 for t in bopts[b'target']:
3712 if t not in KNOWN_TARGET:
3713 raise error.Abort(b"unknown target: %s" % t)
3714 targets.add(t)
3715 targets = sorted(targets)
3716
3717 pairs = set()
3718 prev = None
3719 # gather possible pairs
3720 for rev in rl:
3721 if b'prev' in targets and prev is not None:
3722 pairs.add((prev, rev))
3723 if b'parents' in targets:
3724 for p in rl.parentrevs(rev):
3725 if p > 0:
3726 pairs.add((p, rev))
3727 prev = rev
3728
3729 selected_filter = bopts[b'filter']
3730 if selected_filter:
3731 skip_store = b'storage' not in selected_filter
3732 skip_same = b'common-base' not in selected_filter
3733 skip_other = b'distinct-base' not in selected_filter
3734 old_pairs = pairs
3735 pairs = []
3736 for p in old_pairs:
3737 rev_1, rev_2 = p
3738 if skip_store and rl.deltaparent(rev_2) == rev_1:
3739 continue
3740 base_1 = rl._deltachain(rev_1)[0][0]
3741 base_2 = rl._deltachain(rev_2)[0][0]
3742 if skip_same and base_1 == base_2:
3743 continue
3744 if skip_other and base_1 != base_2:
3745 continue
3746 pairs.append(p)
3747 pairs = sorted(pairs, key=lambda x: (x[1], x[0]))
3748
3749 def setup():
3750 if clear_caches:
3751 rl.index.clearcaches()
3752 rl.clearcaches()
3753
3754 pair_count = len(pairs)
3755
3756 count = [0]
3757
3758 def d():
3759 count[0] += 1
3760 progress = ui.makeprogress(
3761 b"rev-diff #%d" % count[0],
3762 unit=b'pairs',
3763 total=pair_count,
3764 )
3765 with progress:
3766 for idx, (rev_1, rev_2) in enumerate(pairs):
3767 rl.revdiff(rev_1, rev_2)
3768 # update sparsely toi avoid affecting the timing too much.
3769 if (idx % 100) == 0:
3770 progress.increment(100)
3771
3772 timer, fm = gettimer(ui, bopts)
3773 timer(d, setup=setup)
3774 fm.end()
3775
3776
3777 @command(
3778 b'perf::revlogwrite|perfrevlogwrite',
3779 revlogopts
3780 + formatteropts
3781 + [
3782 (b's', b'startrev', 1000, b'revision to start writing at'),
3783 (b'', b'stoprev', -1, b'last revision to write'),
3784 (b'', b'count', 3, b'number of passes to perform'),
3785 (b'', b'details', False, b'print timing for every revisions tested'),
3786 (b'', b'source', b'full', b'the kind of data feed in the revlog'),
3787 (b'', b'lazydeltabase', True, b'try the provided delta first'),
3788 (b'', b'lazy-delta', True, b'try the provided delta first'),
3789 (b'', b'clear-caches', True, b'clear revlog cache between calls'),
3790 ],
3791 b'-c|-m|FILE',
3792 )
3793 def perfrevlogwrite(ui, repo, file_=None, startrev=1000, stoprev=-1, **opts):
3794 """Benchmark writing a series of revisions to a revlog.
3795
3796 Possible source values are:
3797 * `full`: add from a full text (default).
3798 * `parent-1`: add from a delta to the first parent
3799 * `parent-2`: add from a delta to the second parent if it exists
3800 (use a delta from the first parent otherwise)
3801 * `parent-smallest`: add from the smallest delta (either p1 or p2)
3802 * `storage`: add from the existing precomputed deltas
3803
3804 Note: This performance command measures performance in a custom way. As a
3805 result some of the global configuration of the 'perf' command does not
3806 apply to it:
3807
3808 * ``pre-run``: disabled
3809
3810 * ``profile-benchmark``: disabled
3811
3812 * ``run-limits``: disabled use --count instead
3813 """
3814 bopts = _byteskwargs(opts)
3815
3816 rl = cmdutil.openrevlog(repo, b'perfrevlogwrite', file_, bopts)
3817 rllen = getlen(ui)(rl)
3818 if startrev < 0:
3819 startrev = rllen + startrev
3820 if stoprev < 0:
3821 stoprev = rllen + stoprev
3822
3823 lazydeltabase = opts['lazydeltabase']
3824 lazy_delta = opts['lazy_delta']
3825 source = opts['source']
3826 clearcaches = opts['clear_caches']
3827 validsource = (
3828 b'full',
3829 b'parent-1',
3830 b'parent-2',
3831 b'parent-smallest',
3832 b'storage',
3833 )
3834 if source not in validsource:
3835 raise error.Abort('invalid source type: %s' % source)
3836
3837 ### actually gather results
3838 count = opts['count']
3839 if count <= 0:
3840 raise error.Abort('invalide run count: %d' % count)
3841 allresults = []
3842 for c in range(count):
3843 timing = _timeonewrite(
3844 ui,
3845 rl,
3846 source,
3847 startrev,
3848 stoprev,
3849 c + 1,
3850 max_run=count,
3851 lazydeltabase=lazydeltabase,
3852 lazy_delta=lazy_delta,
3853 clearcaches=clearcaches,
3854 )
3855 allresults.append(timing)
3856
3857 ### consolidate the results in a single list
3858 results = []
3859 for idx, (rev, t) in enumerate(allresults[0]):
3860 ts = [t]
3861 for other in allresults[1:]:
3862 orev, ot = other[idx]
3863 assert orev == rev
3864 ts.append(ot)
3865 results.append((rev, ts))
3866 resultcount = len(results)
3867
3868 ### Compute and display relevant statistics
3869
3870 # get a formatter
3871 fm = ui.formatter(b'perf', opts)
3872 displayall = ui.configbool(b"perf", b"all-timing", True)
3873
3874 # print individual details if requested
3875 if opts['details']:
3876 for idx, item in enumerate(results, 1):
3877 rev, data = item
3878 title = b'revisions #%d of %d, rev %d' % (idx, resultcount, rev)
3879 formatone(fm, data, title=title, displayall=displayall)
3880
3881 # sorts results by median time
3882 results.sort(key=lambda x: sorted(x[1])[len(x[1]) // 2])
3883 # list of (name, index) to display)
3884 relevants = [
3885 (b"min", 0),
3886 (b"10%", resultcount * 10 // 100),
3887 (b"25%", resultcount * 25 // 100),
3888 (b"50%", resultcount * 70 // 100),
3889 (b"75%", resultcount * 75 // 100),
3890 (b"90%", resultcount * 90 // 100),
3891 (b"95%", resultcount * 95 // 100),
3892 (b"99%", resultcount * 99 // 100),
3893 (b"99.9%", resultcount * 999 // 1000),
3894 (b"99.99%", resultcount * 9999 // 10000),
3895 (b"99.999%", resultcount * 99999 // 100000),
3896 (b"max", -1),
3897 ]
3898 if not ui.quiet:
3899 for name, idx in relevants:
3900 data = results[idx]
3901 title = b'%s of %d, rev %d' % (name, resultcount, data[0])
3902 formatone(fm, data[1], title=title, displayall=displayall)
3903
3904 # summing that many float loose precisions,
3905 #
3906 # There are advanced technique to reduce this precision lose, but to keep
3907 # things simple, we just sort them to make sure we adds the smaller first,
3908 # reducing the precision lose.
3909 totaltime = []
3910 for item in allresults:
3911 totaltime.append(
3912 (
3913 sum(sorted(x[1][0] for x in item)),
3914 sum(sorted(x[1][1] for x in item)),
3915 sum(sorted(x[1][2] for x in item)),
3916 )
3917 )
3918 formatone(
3919 fm,
3920 totaltime,
3921 title=b"total time (%d revs)" % resultcount,
3922 displayall=displayall,
3923 )
3924 fm.end()
3925
3926
3927 class _faketr:
3928 def add(s, x, y, z=None):
3929 return None
3930
3931
3932 def _timeonewrite(
3933 ui,
3934 orig,
3935 source,
3936 startrev,
3937 stoprev,
3938 runidx=None,
3939 max_run=None,
3940 lazydeltabase=True,
3941 lazy_delta=True,
3942 clearcaches=True,
3943 ):
3944 timings = []
3945 tr = _faketr()
3946 with _temprevlog(ui, orig, startrev) as dest:
3947 if hasattr(dest, "delta_config"):
3948 dest.delta_config.lazy_delta_base = lazydeltabase
3949 dest.delta_config.lazy_delta = lazy_delta
3950 else:
3951 dest._lazydeltabase = lazydeltabase
3952 revs = list(orig.revs(startrev, stoprev))
3953 total = len(revs)
3954 topic = b'adding'
3955 if runidx is not None and max_run is not None:
3956 topic += b' (run #%d/%d)' % (runidx, max_run)
3957 elif runidx is not None:
3958 topic += b' (run #%d)' % runidx
3959 # Support both old and new progress API
3960 if util.safehasattr(ui, 'makeprogress'):
3961 progress = ui.makeprogress(topic, unit=b'revs', total=total)
3962
3963 def updateprogress(pos):
3964 progress.update(pos)
3965
3966 def completeprogress():
3967 progress.complete()
3968
3969 else:
3970
3971 def updateprogress(pos):
3972 ui.progress(topic, pos, unit=b'revs', total=total)
3973
3974 def completeprogress():
3975 ui.progress(topic, None, unit=b'revs', total=total)
3976
3977 with dest._writing(tr):
3978 for idx, rev in enumerate(revs):
3979 updateprogress(idx)
3980 addargs, addkwargs = _getrevisionseed(orig, rev, tr, source)
3981 if clearcaches:
3982 dest.index.clearcaches()
3983 dest.clearcaches()
3984 with timeone() as r:
3985 dest.addrawrevision(*addargs, **addkwargs)
3986 timings.append((rev, r[0]))
3987 updateprogress(total)
3988 completeprogress()
3989 return timings
3990
3991
3992 def _getrevisionseed(orig, rev, tr, source):
3993 from mercurial.node import nullid
3994
3995 linkrev = orig.linkrev(rev)
3996 node = orig.node(rev)
3997 p1, p2 = orig.parents(node)
3998 flags = orig.flags(rev)
3999 cachedelta = None
4000 text = None
4001
4002 if source == b'full':
4003 text = orig._revisiondata(rev, validate=False)
4004 elif source == b'parent-1':
4005 baserev = orig.rev(p1)
4006 cachedelta = CachedDelta(baserev, orig.revdiff(p1, rev))
4007 elif source == b'parent-2':
4008 parent = p2
4009 if p2 == nullid:
4010 parent = p1
4011 baserev = orig.rev(parent)
4012 cachedelta = CachedDelta(baserev, orig.revdiff(parent, rev))
4013 elif source == b'parent-smallest':
4014 p1diff = orig.revdiff(p1, rev)
4015 parent = p1
4016 diff = p1diff
4017 if p2 != nullid:
4018 p2diff = orig.revdiff(p2, rev)
4019 if len(p1diff) > len(p2diff):
4020 parent = p2
4021 diff = p2diff
4022 baserev = orig.rev(parent)
4023 cachedelta = CachedDelta(baserev, diff)
4024 elif source == b'storage':
4025 baserev = orig.deltaparent(rev)
4026 cachedelta = CachedDelta(baserev, orig.revdiff(baserev, rev))
4027
4028 return (
4029 (text, tr, linkrev, p1, p2),
4030 {'node': node, 'flags': flags, 'cachedelta': cachedelta},
4031 )
4032
4033
4034 @contextlib.contextmanager
4035 def _temprevlog(ui, orig, truncaterev):
4036 from mercurial import vfs as vfsmod
4037
4038 if orig._inline:
4039 raise error.Abort('not supporting inline revlog (yet)')
4040 revlogkwargs = {}
4041 k = 'upperboundcomp'
4042 if util.safehasattr(orig, k):
4043 revlogkwargs[k] = getattr(orig, k)
4044
4045 indexfile = getattr(orig, '_indexfile', None)
4046 if indexfile is None:
4047 # compatibility with <= hg-5.8
4048 indexfile = getattr(orig, 'indexfile')
4049 origindexpath = orig.opener.join(indexfile)
4050
4051 datafile = orig._datafile
4052 origdatapath = orig.opener.join(datafile)
4053 radix = b'revlog'
4054 indexname = b'revlog.i'
4055 dataname = b'revlog.d'
4056
4057 tmpdir = tempfile.mkdtemp(prefix='tmp-hgperf-').encode('ascii')
4058 try:
4059 # copy the data file in a temporary directory
4060 ui.debug('copying data in %s\n' % tmpdir)
4061 destindexpath = os.path.join(tmpdir, b'revlog.i')
4062 destdatapath = os.path.join(tmpdir, b'revlog.d')
4063 shutil.copyfile(origindexpath, destindexpath)
4064 shutil.copyfile(origdatapath, destdatapath)
4065
4066 # remove the data we want to add again
4067 ui.debug('truncating data to be rewritten\n')
4068 with open(destindexpath, 'ab') as index:
4069 index.seek(0)
4070 index.truncate(truncaterev * orig.index.entry_size)
4071 with open(destdatapath, 'ab') as data:
4072 data.seek(0)
4073 data.truncate(orig.start(truncaterev))
4074
4075 # instantiate a new revlog from the temporary copy
4076 ui.debug('truncating adding to be rewritten\n')
4077 vfs = vfsmod.vfs(tmpdir)
4078 vfs.options = getattr(orig.opener, 'options', None)
4079
4080 try:
4081 dest = revlog(
4082 vfs,
4083 target=orig.target,
4084 radix=radix,
4085 writable=True,
4086 **revlogkwargs,
4087 )
4088 except TypeError:
4089 dest = revlog(
4090 vfs, indexfile=indexname, datafile=dataname, **revlogkwargs
4091 )
4092 if dest._inline:
4093 raise error.Abort('not supporting inline revlog (yet)')
4094 # make sure internals are initialized
4095 dest.revision(len(dest) - 1)
4096 yield dest
4097 del dest, vfs
4098 finally:
4099 shutil.rmtree(tmpdir, True)
4100
4101
4102 @command(
4103 b'perf::revlogchunks|perfrevlogchunks',
4104 revlogopts
4105 + formatteropts
4106 + [
4107 (b'e', b'engines', b'', b'compression engines to use'),
4108 (b's', b'startrev', 0, b'revision to start at'),
4109 ],
4110 b'-c|-m|FILE',
4111 )
4112 def perfrevlogchunks(ui, repo, file_=None, engines=None, startrev=0, **opts):
4113 """Benchmark operations on revlog chunks.
4114
4115 Logically, each revlog is a collection of fulltext revisions. However,
4116 stored within each revlog are "chunks" of possibly compressed data. This
4117 data needs to be read and decompressed or compressed and written.
4118
4119 This command measures the time it takes to read+decompress and recompress
4120 chunks in a revlog. It effectively isolates I/O and compression performance.
4121 For measurements of higher-level operations like resolving revisions,
4122 see ``perfrevlogrevisions`` and ``perfrevlogrevision``.
4123 """
4124 opts = _byteskwargs(opts)
4125
4126 rl = cmdutil.openrevlog(repo, b'perfrevlogchunks', file_, opts)
4127
4128 if rl.uses_rust:
4129 raise NotImplementedError(
4130 "perfrevlogchunks is not implemented for the Rust revlog"
4131 )
4132
4133 # - _chunkraw was renamed to _getsegmentforrevs
4134 # - _getsegmentforrevs was moved on the inner object
4135 try:
4136 segmentforrevs = rl._inner.get_segment_for_revs
4137 except AttributeError:
4138 try:
4139 segmentforrevs = rl._getsegmentforrevs
4140 except AttributeError:
4141 segmentforrevs = rl._chunkraw
4142
4143 # Verify engines argument.
4144 if engines:
4145 engines = {e.strip() for e in engines.split(b',')}
4146 for engine in engines:
4147 try:
4148 util.compressionengines[engine]
4149 except KeyError:
4150 raise error.Abort(b'unknown compression engine: %s' % engine)
4151 else:
4152 engines = []
4153 for e in util.compengines:
4154 engine = util.compengines[e]
4155 try:
4156 if engine.available():
4157 engine.revlogcompressor().compress(b'dummy')
4158 engines.append(e)
4159 except NotImplementedError:
4160 pass
4161
4162 revs = list(rl.revs(startrev, len(rl) - 1))
4163
4164 @contextlib.contextmanager
4165 def reading(rl):
4166 if getattr(rl, 'reading', None) is not None:
4167 with rl.reading():
4168 yield None
4169 elif rl._inline:
4170 indexfile = getattr(rl, '_indexfile', None)
4171 if indexfile is None:
4172 # compatibility with <= hg-5.8
4173 indexfile = getattr(rl, 'indexfile')
4174 yield getsvfs(repo)(indexfile)
4175 else:
4176 datafile = getattr(rl, 'datafile', getattr(rl, 'datafile'))
4177 yield getsvfs(repo)(datafile)
4178
4179 if getattr(rl, 'reading', None) is not None:
4180
4181 @contextlib.contextmanager
4182 def lazy_reading(rl):
4183 with rl.reading():
4184 yield
4185
4186 else:
4187
4188 @contextlib.contextmanager
4189 def lazy_reading(rl):
4190 yield
4191
4192 def doread():
4193 rl.clearcaches()
4194 for rev in revs:
4195 with lazy_reading(rl):
4196 segmentforrevs(rev, rev)
4197
4198 def doreadcachedfh():
4199 rl.clearcaches()
4200 with reading(rl) as fh:
4201 if fh is not None:
4202 for rev in revs:
4203 segmentforrevs(rev, rev, df=fh)
4204 else:
4205 for rev in revs:
4206 segmentforrevs(rev, rev)
4207
4208 def doreadbatch():
4209 rl.clearcaches()
4210 with lazy_reading(rl):
4211 segmentforrevs(revs[0], revs[-1])
4212
4213 def doreadbatchcachedfh():
4214 rl.clearcaches()
4215 with reading(rl) as fh:
4216 if fh is not None:
4217 segmentforrevs(revs[0], revs[-1], df=fh)
4218 else:
4219 segmentforrevs(revs[0], revs[-1])
4220
4221 def dochunk():
4222 rl.clearcaches()
4223 # chunk used to be available directly on the revlog
4224 _chunk = getattr(rl, '_inner', rl)._chunk
4225 with reading(rl) as fh:
4226 if fh is not None:
4227 for rev in revs:
4228 _chunk(rev, df=fh)
4229 else:
4230 for rev in revs:
4231 _chunk(rev)
4232
4233 chunks = [None]
4234
4235 def dochunkbatch():
4236 rl.clearcaches()
4237 _chunks = getattr(rl, '_inner', rl)._chunks
4238 with reading(rl) as fh:
4239 if fh is not None:
4240 # Save chunks as a side-effect.
4241 chunks[0] = _chunks(revs, df=fh)
4242 else:
4243 # Save chunks as a side-effect.
4244 chunks[0] = _chunks(revs)
4245
4246 def docompress(compressor):
4247 rl.clearcaches()
4248
4249 compressor_holder = getattr(rl, '_inner', rl)
4250
4251 try:
4252 # Swap in the requested compression engine.
4253 oldcompressor = compressor_holder._compressor
4254 compressor_holder._compressor = compressor
4255 for chunk in chunks[0]:
4256 rl.compress(chunk)
4257 finally:
4258 compressor_holder._compressor = oldcompressor
4259
4260 benches = [
4261 (lambda: doread(), b'read'),
4262 (lambda: doreadcachedfh(), b'read w/ reused fd'),
4263 (lambda: doreadbatch(), b'read batch'),
4264 (lambda: doreadbatchcachedfh(), b'read batch w/ reused fd'),
4265 (lambda: dochunk(), b'chunk'),
4266 (lambda: dochunkbatch(), b'chunk batch'),
4267 ]
4268
4269 for engine in sorted(engines):
4270 compressor = util.compengines[engine].revlogcompressor()
4271 benches.append(
4272 (
4273 functools.partial(docompress, compressor),
4274 b'compress w/ %s' % engine,
4275 )
4276 )
4277
4278 for fn, title in benches:
4279 timer, fm = gettimer(ui, opts)
4280 timer(fn, title=title)
4281 fm.end()
4282
4283
4284 @command(
4285 b'perf::revlogrevision|perfrevlogrevision',
4286 revlogopts
4287 + formatteropts
4288 + [(b'', b'cache', False, b'use caches instead of clearing')],
4289 b'-c|-m|FILE REV',
4290 )
4291 def perfrevlogrevision(ui, repo, file_, rev=None, cache=None, **opts):
4292 """Benchmark obtaining a revlog revision.
4293
4294 Obtaining a revlog revision consists of roughly the following steps:
4295
4296 1. Compute the delta chain
4297 2. Slice the delta chain if applicable
4298 3. Obtain the raw chunks for that delta chain
4299 4. Decompress each raw chunk
4300 5. Apply binary patches to obtain fulltext
4301 6. Verify hash of fulltext
4302
4303 This command measures the time spent in each of these phases.
4304 """
4305 opts = _byteskwargs(opts)
4306
4307 if opts.get(b'changelog') or opts.get(b'manifest'):
4308 file_, rev = None, file_
4309 elif rev is None:
4310 raise error.CommandError(b'perfrevlogrevision', b'invalid arguments')
4311
4312 r = cmdutil.openrevlog(repo, b'perfrevlogrevision', file_, opts)
4313 if r.uses_rust:
4314 raise NotImplementedError(
4315 "perfrevlogrevision is not implemented for the Rust revlog"
4316 )
4317
4318 # _chunkraw was renamed to _getsegmentforrevs.
4319 try:
4320 segmentforrevs = r._inner.get_segment_for_revs
4321 except AttributeError:
4322 try:
4323 segmentforrevs = r._getsegmentforrevs
4324 except AttributeError:
4325 segmentforrevs = r._chunkraw
4326
4327 node = r.lookup(rev)
4328 rev = r.rev(node)
4329
4330 if getattr(r, 'reading', None) is not None:
4331
4332 @contextlib.contextmanager
4333 def lazy_reading(r):
4334 with r.reading():
4335 yield
4336
4337 else:
4338
4339 @contextlib.contextmanager
4340 def lazy_reading(r):
4341 yield
4342
4343 def getrawchunks(data, chain):
4344 start = r.start
4345 length = r.length
4346 inline = r._inline
4347 try:
4348 iosize = r.index.entry_size
4349 except AttributeError:
4350 iosize = r._io.size
4351 buffer = util.buffer
4352
4353 chunks = []
4354 ladd = chunks.append
4355 for idx, item in enumerate(chain):
4356 offset = start(item[0])
4357 bits = data[idx]
4358 for rev in item:
4359 chunkstart = start(rev)
4360 if inline:
4361 chunkstart += (rev + 1) * iosize
4362 chunklength = length(rev)
4363 ladd(buffer(bits, chunkstart - offset, chunklength))
4364
4365 return chunks
4366
4367 def dodeltachain(rev):
4368 if not cache:
4369 r.clearcaches()
4370 r._deltachain(rev)
4371
4372 def doread(chain):
4373 if not cache:
4374 r.clearcaches()
4375 for item in slicedchain:
4376 with lazy_reading(r):
4377 segmentforrevs(item[0], item[-1])
4378
4379 def doslice(r, chain, size):
4380 for s in slicechunk(r, chain, targetsize=size):
4381 pass
4382
4383 def dorawchunks(data, chain):
4384 if not cache:
4385 r.clearcaches()
4386 getrawchunks(data, chain)
4387
4388 def dodecompress(chunks):
4389 decomp = r.decompress
4390 for chunk in chunks:
4391 decomp(chunk)
4392
4393 def dopatch(text, bins):
4394 if not cache:
4395 r.clearcaches()
4396 mdiff.patches(text, bins)
4397
4398 def dohash(text):
4399 if not cache:
4400 r.clearcaches()
4401 r.checkhash(text, node, rev=rev)
4402
4403 def dorevision():
4404 if not cache:
4405 r.clearcaches()
4406 r.revision(node)
4407
4408 try:
4409 from mercurial.revlogutils.deltas import slicechunk
4410 except ImportError:
4411 slicechunk = getattr(revlog, '_slicechunk', None)
4412
4413 size = r.length(rev)
4414 chain = r._deltachain(rev)[0]
4415
4416 with_sparse_read = False
4417 if hasattr(r, 'data_config'):
4418 with_sparse_read = r.data_config.with_sparse_read
4419 elif hasattr(r, '_withsparseread'):
4420 with_sparse_read = r._withsparseread
4421 if with_sparse_read:
4422 slicedchain = (chain,)
4423 else:
4424 slicedchain = tuple(slicechunk(r, chain, targetsize=size))
4425 data = [segmentforrevs(seg[0], seg[-1])[1] for seg in slicedchain]
4426 rawchunks = getrawchunks(data, slicedchain)
4427 bins = r._inner._chunks(chain)
4428 text = bytes(bins[0])
4429 bins = bins[1:]
4430 text = mdiff.patches(text, bins)
4431
4432 benches = [
4433 (lambda: dorevision(), b'full'),
4434 (lambda: dodeltachain(rev), b'deltachain'),
4435 (lambda: doread(chain), b'read'),
4436 ]
4437
4438 if with_sparse_read:
4439 slicing = (lambda: doslice(r, chain, size), b'slice-sparse-chain')
4440 benches.append(slicing)
4441
4442 benches.extend(
4443 [
4444 (lambda: dorawchunks(data, slicedchain), b'rawchunks'),
4445 (lambda: dodecompress(rawchunks), b'decompress'),
4446 (lambda: dopatch(text, bins), b'patch'),
4447 (lambda: dohash(text), b'hash'),
4448 ]
4449 )
4450
4451 timer, fm = gettimer(ui, opts)
4452 for fn, title in benches:
4453 timer(fn, title=title)
4454 fm.end()
4455
4456
4457 @command(
4458 b'perf::revset|perfrevset',
4459 [
4460 (b'C', b'clear', False, b'clear volatile cache between each call.'),
4461 (b'', b'contexts', False, b'obtain changectx for each revision'),
4462 ]
4463 + formatteropts,
4464 b"REVSET",
4465 )
4466 def perfrevset(ui, repo, expr, clear=False, contexts=False, **opts):
4467 """benchmark the execution time of a revset
4468
4469 Use the --clean option if need to evaluate the impact of build volatile
4470 revisions set cache on the revset execution. Volatile cache hold filtered
4471 and obsolete related cache."""
4472 opts = _byteskwargs(opts)
4473
4474 timer, fm = gettimer(ui, opts)
4475
4476 def d():
4477 if clear:
4478 repo.invalidatevolatilesets()
4479 if contexts:
4480 for ctx in repo.set(expr):
4481 pass
4482 else:
4483 for r in repo.revs(expr):
4484 pass
4485
4486 timer(d)
4487 fm.end()
4488
4489
4490 @command(
4491 b'perf::volatilesets|perfvolatilesets',
4492 [
4493 (b'', b'clear-obsstore', False, b'drop obsstore between each call.'),
4494 ]
4495 + formatteropts,
4496 )
4497 def perfvolatilesets(ui, repo, *names, **opts):
4498 """benchmark the computation of various volatile set
4499
4500 Volatile set computes element related to filtering and obsolescence."""
4501 opts = _byteskwargs(opts)
4502 timer, fm = gettimer(ui, opts)
4503 repo = repo.unfiltered()
4504
4505 def getobs(name):
4506 def d():
4507 repo.invalidatevolatilesets()
4508 if opts[b'clear_obsstore']:
4509 clearfilecache(repo, b'obsstore')
4510 obsolete.getrevs(repo, name)
4511
4512 return d
4513
4514 allobs = sorted(obsolete.cachefuncs)
4515 if names:
4516 allobs = [n for n in allobs if n in names]
4517
4518 for name in allobs:
4519 timer(getobs(name), title=name)
4520
4521 def getfiltered(name):
4522 def d():
4523 repo.invalidatevolatilesets()
4524 if opts[b'clear_obsstore']:
4525 clearfilecache(repo, b'obsstore')
4526 repoview.filterrevs(repo, name)
4527
4528 return d
4529
4530 allfilter = sorted(repoview.filtertable)
4531 if names:
4532 allfilter = [n for n in allfilter if n in names]
4533
4534 for name in allfilter:
4535 timer(getfiltered(name), title=name)
4536 fm.end()
4537
4538
4539 @command(
4540 b'perf::branchmap|perfbranchmap',
4541 [
4542 (b'f', b'full', False, b'Includes build time of subset'),
4543 (
4544 b'',
4545 b'clear-revbranch',
4546 False,
4547 b'purge the revbranch cache between computation',
4548 ),
4549 ]
4550 + formatteropts,
4551 )
4552 def perfbranchmap(ui, repo, *filternames, **opts):
4553 """benchmark the update of a branchmap
4554
4555 This benchmarks the full repo.branchmap() call with read and write disabled
4556 """
4557 opts = _byteskwargs(opts)
4558 full = opts.get(b"full", False)
4559 clear_revbranch = opts.get(b"clear_revbranch", False)
4560 timer, fm = gettimer(ui, opts)
4561
4562 def getbranchmap(filtername):
4563 """generate a benchmark function for the filtername"""
4564 if filtername is None:
4565 view = repo
4566 else:
4567 view = repo.filtered(filtername)
4568 if util.safehasattr(view._branchcaches, '_per_filter'):
4569 filtered = view._branchcaches._per_filter
4570 else:
4571 # older versions
4572 filtered = view._branchcaches
4573
4574 def d():
4575 if clear_revbranch:
4576 repo.revbranchcache()._clear()
4577 if full:
4578 view._branchcaches.clear()
4579 else:
4580 filtered.pop(filtername, None)
4581 view.branchmap()
4582
4583 return d
4584
4585 # add filter in smaller subset to bigger subset
4586 possiblefilters = set(repoview.filtertable)
4587 if filternames:
4588 possiblefilters &= set(filternames)
4589 subsettable = getbranchmapsubsettable()
4590 allfilters = []
4591 while possiblefilters:
4592 for name in possiblefilters:
4593 subset = subsettable.get(name)
4594 if subset not in possiblefilters:
4595 break
4596 else:
4597 assert False, b'subset cycle %s!' % possiblefilters
4598 allfilters.append(name)
4599 possiblefilters.remove(name)
4600
4601 # warm the cache
4602 if not full:
4603 for name in allfilters:
4604 repo.filtered(name).branchmap()
4605 if not filternames or b'unfiltered' in filternames:
4606 # add unfiltered
4607 allfilters.append(None)
4608
4609 old_branch_cache_from_file = None
4610 branchcacheread = None
4611 if util.safehasattr(branchmap, 'branch_cache_from_file'):
4612 old_branch_cache_from_file = branchmap.branch_cache_from_file
4613 branchmap.branch_cache_from_file = lambda *args: None
4614 elif util.safehasattr(branchmap.branchcache, 'fromfile'):
4615 branchcacheread = safeattrsetter(branchmap.branchcache, b'fromfile')
4616 branchcacheread.set(classmethod(lambda *args: None))
4617 else:
4618 # older versions
4619 branchcacheread = safeattrsetter(branchmap, b'read')
4620 branchcacheread.set(lambda *args: None)
4621 if util.safehasattr(branchmap, '_LocalBranchCache'):
4622 branchcachewrite = safeattrsetter(branchmap._LocalBranchCache, b'write')
4623 branchcachewrite.set(lambda *args: None)
4624 else:
4625 branchcachewrite = safeattrsetter(branchmap.branchcache, b'write')
4626 branchcachewrite.set(lambda *args: None)
4627 try:
4628 for name in allfilters:
4629 printname = name
4630 if name is None:
4631 printname = b'unfiltered'
4632 timer(getbranchmap(name), title=printname)
4633 finally:
4634 if old_branch_cache_from_file is not None:
4635 branchmap.branch_cache_from_file = old_branch_cache_from_file
4636 if branchcacheread is not None:
4637 branchcacheread.restore()
4638 branchcachewrite.restore()
4639 fm.end()
4640
4641
4642 @command(
4643 b'perf::branchmapupdate|perfbranchmapupdate',
4644 [
4645 (b'', b'base', [], b'subset of revision to start from'),
4646 (b'', b'target', [], b'subset of revision to end with'),
4647 (b'', b'clear-caches', False, b'clear cache between each runs'),
4648 ]
4649 + formatteropts,
4650 )
4651 def perfbranchmapupdate(ui, repo, base=(), target=(), **opts):
4652 """benchmark branchmap update from for <base> revs to <target> revs
4653
4654 If `--clear-caches` is passed, the following items will be reset before
4655 each update:
4656 * the changelog instance and associated indexes
4657 * the rev-branch-cache instance
4658
4659 Examples:
4660
4661 # update for the one last revision
4662 $ hg perfbranchmapupdate --base 'not tip' --target 'tip'
4663
4664 $ update for change coming with a new branch
4665 $ hg perfbranchmapupdate --base 'stable' --target 'default'
4666 """
4667 from mercurial import branchmap
4668 from mercurial import repoview
4669
4670 opts = _byteskwargs(opts)
4671 timer, fm = gettimer(ui, opts)
4672 clearcaches = opts[b'clear_caches']
4673 unfi = repo.unfiltered()
4674 x = [None] # used to pass data between closure
4675
4676 # we use a `list` here to avoid possible side effect from smartset
4677 baserevs = list(scmutil.revrange(repo, base))
4678 targetrevs = list(scmutil.revrange(repo, target))
4679 if not baserevs:
4680 raise error.Abort(b'no revisions selected for --base')
4681 if not targetrevs:
4682 raise error.Abort(b'no revisions selected for --target')
4683
4684 # make sure the target branchmap also contains the one in the base
4685 targetrevs = list(set(baserevs) | set(targetrevs))
4686 targetrevs.sort()
4687
4688 cl = repo.changelog
4689 allbaserevs = list(cl.ancestors(baserevs, inclusive=True))
4690 allbaserevs.sort()
4691 alltargetrevs = frozenset(cl.ancestors(targetrevs, inclusive=True))
4692
4693 newrevs = list(alltargetrevs.difference(allbaserevs))
4694 newrevs.sort()
4695
4696 allrevs = frozenset(unfi.changelog.revs())
4697 basefilterrevs = frozenset(allrevs.difference(allbaserevs))
4698 targetfilterrevs = frozenset(allrevs.difference(alltargetrevs))
4699
4700 def basefilter(repo, visibilityexceptions=None):
4701 return basefilterrevs
4702
4703 def targetfilter(repo, visibilityexceptions=None):
4704 return targetfilterrevs
4705
4706 msg = b'benchmark of branchmap with %d revisions with %d new ones\n'
4707 ui.status(msg % (len(allbaserevs), len(newrevs)))
4708 if targetfilterrevs:
4709 msg = b'(%d revisions still filtered)\n'
4710 ui.status(msg % len(targetfilterrevs))
4711
4712 try:
4713 repoview.filtertable[b'__perf_branchmap_update_base'] = basefilter
4714 repoview.filtertable[b'__perf_branchmap_update_target'] = targetfilter
4715
4716 baserepo = repo.filtered(b'__perf_branchmap_update_base')
4717 targetrepo = repo.filtered(b'__perf_branchmap_update_target')
4718
4719 bcache = repo.branchmap()
4720 copy_method = 'copy'
4721
4722 copy_base_kwargs = copy_base_kwargs = {}
4723 if hasattr(bcache, 'copy'):
4724 if 'repo' in getargspec(bcache.copy).args:
4725 copy_base_kwargs = {"repo": baserepo}
4726 copy_target_kwargs = {"repo": targetrepo}
4727 else:
4728 copy_method = 'inherit_for'
4729 copy_base_kwargs = {"repo": baserepo}
4730 copy_target_kwargs = {"repo": targetrepo}
4731
4732 # try to find an existing branchmap to reuse
4733 subsettable = getbranchmapsubsettable()
4734 candidatefilter = subsettable.get(None)
4735 while candidatefilter is not None:
4736 candidatebm = repo.filtered(candidatefilter).branchmap()
4737 if candidatebm.validfor(baserepo):
4738 filtered = repoview.filterrevs(repo, candidatefilter)
4739 missing = [r for r in allbaserevs if r in filtered]
4740 base = getattr(candidatebm, copy_method)(**copy_base_kwargs)
4741 base.update(baserepo, missing)
4742 break
4743 candidatefilter = subsettable.get(candidatefilter)
4744 else:
4745 # no suitable subset where found
4746 base = branchmap.branchcache()
4747 base.update(baserepo, allbaserevs)
4748
4749 def setup():
4750 x[0] = getattr(base, copy_method)(**copy_target_kwargs)
4751 if clearcaches:
4752 unfi._revbranchcache = None
4753 clearchangelog(repo)
4754
4755 def bench():
4756 x[0].update(targetrepo, newrevs)
4757
4758 timer(bench, setup=setup)
4759 fm.end()
4760 finally:
4761 repoview.filtertable.pop(b'__perf_branchmap_update_base', None)
4762 repoview.filtertable.pop(b'__perf_branchmap_update_target', None)
4763
4764
4765 @command(
4766 b'perf::branchmapload|perfbranchmapload',
4767 [
4768 (b'f', b'filter', b'', b'Specify repoview filter'),
4769 (b'', b'list', False, b'List brachmap filter caches'),
4770 (b'', b'clear-revlogs', False, b'refresh changelog and manifest'),
4771 ]
4772 + formatteropts,
4773 )
4774 def perfbranchmapload(ui, repo, filter=b'', list=False, **opts):
4775 """benchmark reading the branchmap"""
4776 opts = _byteskwargs(opts)
4777 clearrevlogs = opts[b'clear_revlogs']
4778
4779 if list:
4780 for name, kind, st in repo.cachevfs.readdir(stat=True):
4781 if name.startswith(b'branch2'):
4782 filtername = name.partition(b'-')[2] or b'unfiltered'
4783 ui.status(
4784 b'%s - %s\n' % (filtername, util.bytecount(st.st_size))
4785 )
4786 return
4787 if not filter:
4788 filter = None
4789 subsettable = getbranchmapsubsettable()
4790 if filter is None:
4791 repo = repo.unfiltered()
4792 else:
4793 repo = repoview.repoview(repo, filter)
4794
4795 repo.branchmap() # make sure we have a relevant, up to date branchmap
4796
4797 fromfile = getattr(branchmap, 'branch_cache_from_file', None)
4798 if fromfile is None:
4799 fromfile = getattr(branchmap.branchcache, 'fromfile', None)
4800 if fromfile is None:
4801 fromfile = branchmap.read
4802
4803 currentfilter = filter
4804 # try once without timer, the filter may not be cached
4805 while fromfile(repo) is None:
4806 currentfilter = subsettable.get(currentfilter)
4807 if currentfilter is None:
4808 raise error.Abort(
4809 b'No branchmap cached for %s repo' % (filter or b'unfiltered')
4810 )
4811 repo = repo.filtered(currentfilter)
4812 timer, fm = gettimer(ui, opts)
4813
4814 def setup():
4815 if clearrevlogs:
4816 clearchangelog(repo)
4817
4818 def bench():
4819 fromfile(repo)
4820
4821 timer(bench, setup=setup)
4822 fm.end()
4823
4824
4825 @command(b'perf::loadmarkers|perfloadmarkers')
4826 def perfloadmarkers(ui, repo):
4827 """benchmark the time to parse the on-disk markers for a repo
4828
4829 Result is the number of markers in the repo."""
4830 timer, fm = gettimer(ui)
4831 svfs = getsvfs(repo)
4832 timer(lambda: len(obsolete.obsstore(repo, svfs)))
4833 fm.end()
4834
4835
4836 @command(
4837 b'perf::lrucachedict|perflrucachedict',
4838 formatteropts
4839 + [
4840 (b'', b'costlimit', 0, b'maximum total cost of items in cache'),
4841 (b'', b'mincost', 0, b'smallest cost of items in cache'),
4842 (b'', b'maxcost', 100, b'maximum cost of items in cache'),
4843 (b'', b'size', 4, b'size of cache'),
4844 (b'', b'gets', 10000, b'number of key lookups'),
4845 (b'', b'sets', 10000, b'number of key sets'),
4846 (b'', b'mixed', 10000, b'number of mixed mode operations'),
4847 (
4848 b'',
4849 b'mixedgetfreq',
4850 50,
4851 b'frequency of get vs set ops in mixed mode',
4852 ),
4853 ],
4854 norepo=True,
4855 )
4856 def perflrucache(
4857 ui,
4858 mincost=0,
4859 maxcost=100,
4860 costlimit=0,
4861 size=4,
4862 gets=10000,
4863 sets=10000,
4864 mixed=10000,
4865 mixedgetfreq=50,
4866 **opts,
4867 ):
4868 opts = _byteskwargs(opts)
4869
4870 def doinit():
4871 for i in _xrange(10000):
4872 util.lrucachedict(size)
4873
4874 costrange = list(range(mincost, maxcost + 1))
4875
4876 values = []
4877 for i in _xrange(size):
4878 values.append(random.randint(0, _maxint))
4879
4880 # Get mode fills the cache and tests raw lookup performance with no
4881 # eviction.
4882 getseq = []
4883 for i in _xrange(gets):
4884 getseq.append(random.choice(values))
4885
4886 def dogets():
4887 d = util.lrucachedict(size)
4888 for v in values:
4889 d[v] = v
4890 for key in getseq:
4891 value = d[key]
4892 value # silence pyflakes warning
4893
4894 def dogetscost():
4895 d = util.lrucachedict(size, maxcost=costlimit)
4896 for i, v in enumerate(values):
4897 d.insert(v, v, cost=costs[i])
4898 for key in getseq:
4899 try:
4900 value = d[key]
4901 value # silence pyflakes warning
4902 except KeyError:
4903 pass
4904
4905 # Set mode tests insertion speed with cache eviction.
4906 setseq = []
4907 costs = []
4908 for i in _xrange(sets):
4909 setseq.append(random.randint(0, _maxint))
4910 costs.append(random.choice(costrange))
4911
4912 def doinserts():
4913 d = util.lrucachedict(size)
4914 for v in setseq:
4915 d.insert(v, v)
4916
4917 def doinsertscost():
4918 d = util.lrucachedict(size, maxcost=costlimit)
4919 for i, v in enumerate(setseq):
4920 d.insert(v, v, cost=costs[i])
4921
4922 def dosets():
4923 d = util.lrucachedict(size)
4924 for v in setseq:
4925 d[v] = v
4926
4927 # Mixed mode randomly performs gets and sets with eviction.
4928 mixedops = []
4929 for i in _xrange(mixed):
4930 r = random.randint(0, 100)
4931 if r < mixedgetfreq:
4932 op = 0
4933 else:
4934 op = 1
4935
4936 mixedops.append(
4937 (op, random.randint(0, size * 2), random.choice(costrange))
4938 )
4939
4940 def domixed():
4941 d = util.lrucachedict(size)
4942
4943 for op, v, cost in mixedops:
4944 if op == 0:
4945 try:
4946 d[v]
4947 except KeyError:
4948 pass
4949 else:
4950 d[v] = v
4951
4952 def domixedcost():
4953 d = util.lrucachedict(size, maxcost=costlimit)
4954
4955 for op, v, cost in mixedops:
4956 if op == 0:
4957 try:
4958 d[v]
4959 except KeyError:
4960 pass
4961 else:
4962 d.insert(v, v, cost=cost)
4963
4964 benches = [
4965 (doinit, b'init'),
4966 ]
4967
4968 if costlimit:
4969 benches.extend(
4970 [
4971 (dogetscost, b'gets w/ cost limit'),
4972 (doinsertscost, b'inserts w/ cost limit'),
4973 (domixedcost, b'mixed w/ cost limit'),
4974 ]
4975 )
4976 else:
4977 benches.extend(
4978 [
4979 (dogets, b'gets'),
4980 (doinserts, b'inserts'),
4981 (dosets, b'sets'),
4982 (domixed, b'mixed'),
4983 ]
4984 )
4985
4986 for fn, title in benches:
4987 timer, fm = gettimer(ui, opts)
4988 timer(fn, title=title)
4989 fm.end()
4990
4991
4992 @command(
4993 b'perf::write|perfwrite',
4994 formatteropts
4995 + [
4996 (b'', b'write-method', b'write', b'ui write method'),
4997 (b'', b'nlines', 100, b'number of lines'),
4998 (b'', b'nitems', 100, b'number of items (per line)'),
4999 (b'', b'item', b'x', b'item that is written'),
5000 (b'', b'batch-line', None, b'pass whole line to write method at once'),
5001 (b'', b'flush-line', None, b'flush after each line'),
5002 ],
5003 )
5004 def perfwrite(ui, repo, **opts):
5005 """microbenchmark ui.write (and others)"""
5006 opts = _byteskwargs(opts)
5007
5008 write = getattr(ui, _sysstr(opts[b'write_method']))
5009 nlines = int(opts[b'nlines'])
5010 nitems = int(opts[b'nitems'])
5011 item = opts[b'item']
5012 batch_line = opts.get(b'batch_line')
5013 flush_line = opts.get(b'flush_line')
5014
5015 if batch_line:
5016 line = item * nitems + b'\n'
5017
5018 def benchmark():
5019 for i in pycompat.xrange(nlines):
5020 if batch_line:
5021 write(line)
5022 else:
5023 for i in pycompat.xrange(nitems):
5024 write(item)
5025 write(b'\n')
5026 if flush_line:
5027 ui.flush()
5028 ui.flush()
5029
5030 timer, fm = gettimer(ui, opts)
5031 timer(benchmark)
5032 fm.end()
5033
5034
5035 def uisetup(ui):
5036 if util.safehasattr(cmdutil, b'openrevlog') and not util.safehasattr(
5037 commands, b'debugrevlogopts'
5038 ):
5039 # for "historical portability":
5040 # In this case, Mercurial should be 1.9 (or a79fea6b3e77) -
5041 # 3.7 (or 5606f7d0d063). Therefore, '--dir' option for
5042 # openrevlog() should cause failure, because it has been
5043 # available since 3.5 (or 49c583ca48c4).
5044 def openrevlog(orig, repo, cmd, file_, opts):
5045 if opts.get(b'dir') and not util.safehasattr(repo, b'dirlog'):
5046 raise error.Abort(
5047 b"This version doesn't support --dir option",
5048 hint=b"use 3.5 or later",
5049 )
5050 return orig(repo, cmd, file_, opts)
5051
5052 name = _sysstr(b'openrevlog')
5053 extensions.wrapfunction(cmdutil, name, openrevlog)
5054
5055
5056 @command(
5057 b'perf::progress|perfprogress',
5058 formatteropts
5059 + [
5060 (b'', b'topic', b'topic', b'topic for progress messages'),
5061 (b'c', b'total', 1000000, b'total value we are progressing to'),
5062 ],
5063 norepo=True,
5064 )
5065 def perfprogress(ui, topic=None, total=None, **opts):
5066 """printing of progress bars"""
5067 opts = _byteskwargs(opts)
5068
5069 timer, fm = gettimer(ui, opts)
5070
5071 def doprogress():
5072 with ui.makeprogress(topic, total=total) as progress:
5073 for i in _xrange(total):
5074 progress.increment()
5075
5076 timer(doprogress)
5077 fm.end()