Debugging Performance Issues

Most chapters of this book deal with functional issues – that is, issues related to the functionality (or its absence) of the code in question. However, debugging can also involve nonfunctional issues, however – performance, usability, reliability, and more. In this chapter, we give a short introduction on how to debug such nonfunctional issues, notably performance issues.

from bookutils import YouTubeVideo
YouTubeVideo("0tMeB9G0uUI")

Prerequisites

Synopsis

To use the code provided in this chapter, write

>>> from debuggingbook.PerformanceDebugger import <identifier>

and then make use of the following features.

This chapter provides a class PerformanceDebugger that allows measuring and visualizing the time taken per line in a function.

>>> with PerformanceDebugger(TimeCollector) as debugger:
>>>     for i in range(100):
>>>         s = remove_html_markup('<b>foo</b>')

The distribution of executed time within each function can be obtained by printing out the debugger:

>>> print(debugger)
 238   2% def remove_html_markup(s):
 239   2%     tag = False
 240   1%     quote = False
 241   1%     out = ""
 242   0%
 243  16%     for c in s:
 244  15%         assert tag or not quote
 245   0%
 246  15%         if c == '<' and not quote:
 247   3%             tag = True
 248  12%         elif c == '>' and not quote:
 249   3%             tag = False
 250   9%         elif (c == '"' or c == "'") and tag:
 251   0%             quote = not quote
 252   9%         elif not tag:
 253   4%             out = out + c
 254   0%
 255   3%     return out

The sum of all percentages in a function should always be 100%.

These percentages can also be visualized, where darker shades represent higher percentage values:

>>> debugger
 238 def remove_html_markup(s):  # type: ignore
 239     tag = False
 240     quote = False
 241     out = ""
 242  
 243     for c in s:
 244         assert tag or not quote
 245  
 246         if c == '<' and not quote:
 247             tag = True
 248         elif c == '>' and not quote:
 249             tag = False
 250         elif (c == '"' or c == "'") and tag:
 251             quote = not quote
 252         elif not tag:
 253             out = out + c
 254  
 255     return out

The abstract MetricCollector class allows subclassing to build more collectors, such as HitCollector.

PerformanceDebugger PerformanceDebugger __init__() MetricDebugger MetricDebugger color() maximum() metric() suspiciousness() tooltip() total() PerformanceDebugger->MetricDebugger SpectrumDebugger SpectrumDebugger MetricDebugger->SpectrumDebugger DifferenceDebugger DifferenceDebugger FAIL PASS SpectrumDebugger->DifferenceDebugger StatisticalDebugger StatisticalDebugger DifferenceDebugger->StatisticalDebugger TimeCollector TimeCollector __enter__() __init__() all_metrics() collect() metric() reset_timer() MetricCollector MetricCollector all_metrics() maximum() metric() total() TimeCollector->MetricCollector CoverageCollector CoverageCollector MetricCollector->CoverageCollector Collector Collector CoverageCollector->Collector StackInspector StackInspector _generated_function_cache CoverageCollector->StackInspector Tracer Tracer Collector->Tracer Tracer->StackInspector HitCollector HitCollector __init__() all_metrics() collect() metric() HitCollector->MetricCollector Legend Legend •  public_method() •  private_method() •  overloaded_method() Hover over names to see doc

Measuring Performance

The solution to debugging performance issues fits in two simple rules:

  1. Measure performance
  2. Break down how individual parts of your code contribute to performance.

The first part, actually measuring performance, is key here. Developers often take elaborated guesses on which aspects of their code impact performance, and think about all possible ways to optimize their code – and at the same time, making it harder to understand, harder to evolve, and harder to maintain. In most cases, such guesses are wrong. Instead, measure performance of your program, identify the very few parts that may need to get improved, and again measure the impact of your changes.

Almost all programming languages offer a way to measure performance and breaking it down to individual parts of the code – a means also known as profiling. Profiling works by measuring the execution time for each function (or even more fine-grained location) in your program. This can be achieved by

  1. Instrumenting or tracing code such that the current time at entry and exit of each function (or line), thus determining the time spent. In Python, this is achieved by profilers like profile or cProfile

  2. Sampling the current function call stack at regular intervals, and thus assessing which functions are most active (= take the most time) during execution. For Python, the scalene profiler works this way.

Pretty much all programming languages support profiling, either through measuring, sampling, or both. As a rule of thumb, interpreted languages more frequently support measuring (as it is easy to implement in an interpreter), while compiled languages more frequently support sampling (because instrumentation requires recompilation). Python is lucky to support both methods.

Tracing Execution Profiles

Let us illustrate profiling in a simple example. The ChangeCounter class (which we will encounter in the chapter on mining version histories) reads in a version history from a git repository. Yet, it takes more than a minute to read in the debugging book change history:

from ChangeCounter import ChangeCounter, debuggingbook_change_counter  # minor dependency
import Timer
with Timer.Timer() as t:
    change_counter = debuggingbook_change_counter(ChangeCounter)
t.elapsed_time()
349.07027487503365

The Python profile and cProfile modules offer a simple way to identify the most time-consuming functions. They are invoked using the run() function, whose argument is the command to be profiled. The output reports, for each function encountered:

  • How often it was called (ncalls column)
  • How much time was spent in the given function, excluding time spent in calls to sub-functions (tottime column)
  • The fraction of tottime / ncalls (first percall column)
  • How much time was spent in the given function, including time spent in calls to sub-functions (cumtime column)
  • The fraction of cumtime / percall (second percall column)

Let us have a look at the profile we obtain:

import cProfile
cProfile.run('debuggingbook_change_counter(ChangeCounter)', sort='cumulative')
         22156263 function calls (21994125 primitive calls) in 363.626 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000  363.626  363.626 {built-in method builtins.exec}
        1    0.000    0.000  363.626  363.626 <string>:1(<module>)
        1    0.000    0.000  363.625  363.625 ChangeCounter.ipynb:168(debuggingbook_change_counter)
        1    0.002    0.002  363.625  363.625 ChangeCounter.ipynb:51(__init__)
        1    1.974    1.974  363.624  363.624 ChangeCounter.ipynb:88(mine)
     1270    0.048    0.000  361.208    0.284 ChangeCounter.ipynb:102(mine_commit)
     1270    0.123    0.000  360.621    0.284 commit.py:680(modified_files)
     1270    0.049    0.000  360.496    0.284 commit.py:696(_get_modified_files)
     1270    0.199    0.000  203.833    0.160 commit.py:730(_parse_diff)
    26940    0.080    0.000  200.031    0.007 commit.py:759(_get_undecoded_content)
    89938    0.200    0.000  197.360    0.002 cmd.py:528(read)
    76010    0.046    0.000  197.245    0.003 base.py:137(read)
   179854  197.144    0.001  197.144    0.001 {method 'read' of '_io.BufferedReader' objects}
     1220    0.310    0.000  156.512    0.128 diff.py:95(diff)
     1220   21.631    0.018  142.688    0.117 diff.py:445(_index_from_patch_format)
     1220    0.088    0.000   96.655    0.079 cmd.py:71(handle_process_output)
    12302   95.982    0.008   95.982    0.008 {method 'acquire' of '_thread.lock' objects}
     2442    0.017    0.000   95.787    0.039 threading.py:1057(join)
     2442    0.017    0.000   95.766    0.039 threading.py:1095(_wait_for_tstate_lock)
    13470    0.154    0.000   23.218    0.002 diff.py:290(__init__)
    12658    0.030    0.000   22.744    0.002 base.py:363(submodules)
    12658    0.068    0.000   22.714    0.002 util.py:1092(list_items)
26228/26225    0.049    0.000   22.626    0.001 {method 'extend' of 'list' objects}
    37974    0.210    0.000   22.577    0.001 base.py:1228(iter_items)
     1269    0.117    0.000   14.169    0.011 cmd.py:1114(_call_process)
     1269    0.189    0.000   14.025    0.011 cmd.py:726(execute)
     1221    0.047    0.000   13.512    0.011 cmd.py:638(<lambda>)
     1269    0.260    0.000   13.432    0.011 subprocess.py:753(__init__)
     1269    0.312    0.000   13.083    0.010 subprocess.py:1682(_execute_child)
   140570    0.575    0.000   10.738    0.000 cmd.py:1235(__get_object_header)
    89938    0.208    0.000    9.478    0.000 db.py:46(stream)
    89938    0.316    0.000    9.138    0.000 cmd.py:1263(stream_object_data)
     1269    8.967    0.007    8.967    0.007 {built-in method _posixsubprocess.fork_exec}
    65780    0.084    0.000    8.915    0.000 util.py:248(__getattr__)
    37974    0.051    0.000    7.801    0.000 base.py:527(commit)
   232009    7.465    0.000    7.479    0.000 {method 'readline' of '_io.BufferedReader' objects}
88606/25316    0.061    0.000    7.197    0.000 tree.py:347(__getitem__)
88606/25316    0.244    0.000    7.164    0.000 tree.py:245(join)
    37974    0.028    0.000    6.743    0.000 symbolic.py:212(_get_commit)
    37974    0.057    0.000    6.714    0.000 symbolic.py:203(_get_object)
    50632    0.082    0.000    6.562    0.000 tree.py:224(_set_cache_)
    50632    0.043    0.000    5.762    0.000 symbolic.py:143(dereference_recursive)
   101265    0.121    0.000    5.719    0.000 symbolic.py:196(_get_ref_info)
   101265    0.343    0.000    5.597    0.000 symbolic.py:156(_get_ref_info_helper)
    50632    0.148    0.000    3.564    0.000 base.py:75(new_from_sha)
    12658    0.072    0.000    3.472    0.000 base.py:196(_config_parser)
    25378    0.051    0.000    3.282    0.000 base.py:129(data_stream)
    50632    0.131    0.000    3.038    0.000 db.py:42(info)
     1269    2.964    0.002    2.964    0.002 {built-in method posix.read}
    12658    0.081    0.000    2.846    0.000 fun.py:191(rev_parse)
    50632    0.050    0.000    2.842    0.000 cmd.py:1243(get_object_header)
    12658    0.061    0.000    2.753    0.000 fun.py:121(name_to_object)
   101449    2.588    0.000    2.688    0.000 {method 'read' of '_io.TextIOWrapper' objects}
  1062392    2.639    0.000    2.639    0.000 {method 'decode' of 'bytes' objects}
    13470    0.010    0.000    2.517    0.000 commit.py:749(_get_decoded_str)
   116883    2.198    0.000    2.271    0.000 {built-in method io.open}
    15148    0.067    0.000    2.256    0.000 commit.py:196(_set_cache_)
   140570    1.677    0.000    1.789    0.000 cmd.py:1207(_prepare_ref)
101550/88701    0.092    0.000    1.715    0.000 config.py:104(assure_data_present)
    12658    0.049    0.000    1.458    0.000 util.py:72(__init__)
    12752    0.075    0.000    1.421    0.000 config.py:281(__init__)
    12752    0.083    0.000    1.337    0.000 configparser.py:601(__init__)
101550/88798    0.116    0.000    1.328    0.000 config.py:543(read)
    50632    0.873    0.000    1.137    0.000 fun.py:59(tree_entries_from_data)
     1220    1.062    0.001    1.062    0.001 {method 'join' of 'bytes' objects}
    12752    0.229    0.000    1.021    0.000 configparser.py:1321(__init__)
    13470    0.074    0.000    0.959    0.000 commit.py:155(__init__)
    25642    0.048    0.000    0.885    0.000 pathlib.py:955(__new__)
    12752    0.291    0.000    0.879    0.000 config.py:391(_read)
    25644    0.033    0.000    0.836    0.000 pathlib.py:587(_from_parts)
    25644    0.075    0.000    0.798    0.000 pathlib.py:567(_parse_args)
   140570    0.037    0.000    0.768    0.000 cmd.py:1221(_get_persistent_cmd)
   140570    0.710    0.000    0.714    0.000 {method 'flush' of '_io.BufferedWriter' objects}
    25644    0.128    0.000    0.704    0.000 pathlib.py:56(parse_parts)
    14740    0.008    0.000    0.599    0.000 commit.py:587(committer_date)
    14740    0.010    0.000    0.591    0.000 commit.py:209(committed_datetime)
    12752    0.581    0.000    0.581    0.000 {built-in method builtins.dir}
    13928    0.136    0.000    0.534    0.000 commit.py:525(_deserialize)
     1269    0.250    0.000    0.524    0.000 subprocess.py:1222(_close_pipe_fds)
    97344    0.515    0.000    0.515    0.000 {built-in method sys.intern}
     1271    0.002    0.000    0.441    0.000 repository.py:207(traverse_commits)
     2442    0.028    0.000    0.426    0.000 threading.py:909(start)
     1274    0.047    0.000    0.370    0.000 repository.py:246(_iter_commits)
  1761384    0.334    0.000    0.334    0.000 {method 'match' of 're.Pattern' objects}
    14740    0.025    0.000    0.306    0.000 util.py:167(from_timestamp)
   140570    0.233    0.000    0.306    0.000 cmd.py:1185(_parse_object_header)
   144419    0.194    0.000    0.299    0.000 posixpath.py:71(join)
     2443    0.016    0.000    0.293    0.000 threading.py:582(wait)
     2443    0.015    0.000    0.267    0.000 threading.py:288(wait)
    50725    0.066    0.000    0.265    0.000 configparser.py:766(get)
     2442    0.032    0.000    0.261    0.000 ipkernel.py:768(init_closure)
   882728    0.162    0.000    0.252    0.000 cmd.py:466(__getattr__)
    27856    0.057    0.000    0.252    0.000 util.py:268(parse_actor_and_date)
     1269    0.045    0.000    0.236    0.000 os.py:711(copy)
   443030    0.134    0.000    0.231    0.000 compat.py:49(safe_decode)
    50632    0.135    0.000    0.229    0.000 util.py:85(get_object_type_by_name)
     2442    0.082    0.000    0.229    0.000 threading.py:820(__init__)
   114204    0.218    0.000    0.218    0.000 {method '__exit__' of '_io._IOBase' objects}
    12752    0.106    0.000    0.215    0.000 configparser.py:1244(__init__)
   168476    0.156    0.000    0.203    0.000 base.py:50(__init__)
     2586    0.068    0.000    0.201    0.000 contextlib.py:496(callback)
   102596    0.089    0.000    0.192    0.000 base.py:153(__init__)
    14740    0.189    0.000    0.192    0.000 {built-in method fromtimestamp}
1153445/1153443    0.189    0.000    0.191    0.000 {built-in method builtins.getattr}
    25640    0.126    0.000    0.184    0.000 util.py:69(mode_str_to_int)
    65880    0.063    0.000    0.165    0.000 commit.py:84(__init__)
    51902    0.046    0.000    0.157    0.000 tree.py:214(__init__)
     1269    0.022    0.000    0.149    0.000 util.py:412(remove_password_if_present)
1869541/1869537    0.129    0.000    0.136    0.000 {built-in method builtins.isinstance}
    25316    0.021    0.000    0.126    0.000 base.py:335(index)
     1309    0.020    0.000    0.126    0.000 cmd.py:463(__del__)
      804    0.041    0.000    0.126    0.000 ChangeCounter.ipynb:121(update_stats)
    81473    0.117    0.000    0.121    0.000 {method 'search' of 're.Pattern' objects}
    50725    0.065    0.000    0.116    0.000 configparser.py:1143(_unify_values)
    88698    0.084    0.000    0.110    0.000 util.py:163(join_path)
    92730    0.055    0.000    0.108    0.000 os.py:674(__getitem__)
    12350    0.052    0.000    0.107    0.000 parse.py:437(urlsplit)
    25316    0.032    0.000    0.106    0.000 base.py:117(__init__)
     1269    0.037    0.000    0.105    0.000 os.py:619(get_exec_path)
     2442    0.102    0.000    0.102    0.000 {built-in method _thread.start_new_thread}
   101449    0.073    0.000    0.100    0.000 codecs.py:319(decode)
   220806    0.059    0.000    0.098    0.000 os.py:804(fsencode)
    27856    0.028    0.000    0.098    0.000 util.py:665(_from_string)
     1309    0.053    0.000    0.092    0.000 cmd.py:421(_terminate)
   232423    0.087    0.000    0.092    0.000 {method 'split' of 'str' objects}
     2586    0.021    0.000    0.090    0.000 contextlib.py:514(_push_exit_callback)
    12755    0.015    0.000    0.088    0.000 config.py:489(_has_includes)
    13470    0.046    0.000    0.085    0.000 commit.py:923(_from_change_to_modification_type)
       92    0.000    0.000    0.085    0.001 util.py:98(wrapper)
       92    0.000    0.000    0.085    0.001 base.py:1103(module)
       93    0.004    0.000    0.084    0.001 base.py:108(__init__)
    25316    0.029    0.000    0.079    0.000 base.py:114(__init__)
     1221    0.017    0.000    0.079    0.000 util.py:383(finalize_process)
    13470    0.009    0.000    0.078    0.000 ChangeCounter.ipynb:112(include)
    30456    0.015    0.000    0.077    0.000 subprocess.py:1770(<genexpr>)
   801006    0.077    0.000    0.077    0.000 {built-in method builtins.len}
    93906    0.017    0.000    0.076    0.000 _collections_abc.py:877(__iter__)
    25316    0.021    0.000    0.074    0.000 base.py:157(_index_path)
    50725    0.051    0.000    0.074    0.000 __init__.py:976(__getitem__)
   101449    0.048    0.000    0.073    0.000 codecs.py:309(__init__)
    12752    0.020    0.000    0.072    0.000 config.py:492(_included_paths)
     2443    0.010    0.000    0.072    0.000 threading.py:538(__init__)
    26940    0.011    0.000    0.072    0.000 diff.py:432(_pick_best_path)
   101265    0.053    0.000    0.072    0.000 symbolic.py:43(_git_dir)
    89757    0.070    0.000    0.072    0.000 config.py:180(__setitem__)
     5029    0.070    0.000    0.070    0.000 {method 'append' of 'collections.deque' objects}
    13470    0.015    0.000    0.069    0.000 ChangeCounter.ipynb:176(filter)
     2441    0.032    0.000    0.068    0.000 cmd.py:470(wait)
    14740    0.062    0.000    0.066    0.000 {method 'astimezone' of 'datetime.datetime' objects}
     2485    0.009    0.000    0.062    0.000 subprocess.py:1199(wait)
    37975    0.023    0.000    0.062    0.000 base.py:342(head)
   126812    0.050    0.000    0.061    0.000 config.py:192(__getitem__)
   319184    0.061    0.000    0.061    0.000 {method 'endswith' of 'str' objects}
    26940    0.038    0.000    0.061    0.000 diff.py:54(decode_path)
   746395    0.060    0.000    0.060    0.000 {method 'append' of 'list' objects}
    93906    0.038    0.000    0.059    0.000 os.py:697(__iter__)
    89938    0.036    0.000    0.059    0.000 base.py:128(__new__)
   454238    0.058    0.000    0.058    0.000 {method 'encode' of 'str' objects}
       46    0.000    0.000    0.057    0.001 base.py:1121(module_exists)
     1736    0.020    0.000    0.056    0.000 ipkernel.py:775(_clean_thread_parent_frames)
     2485    0.009    0.000    0.053    0.000 subprocess.py:1906(_wait)
    25408    0.016    0.000    0.053    0.000 util.py:200(join_path_native)
    32789    0.019    0.000    0.052    0.000 commit.py:243(new_path)
     1269    0.042    0.000    0.050    0.000 contextlib.py:533(__exit__)
   260615    0.049    0.000    0.049    0.000 {method 'startswith' of 'str' objects}
   153840    0.049    0.000    0.049    0.000 typing.py:305(inner)
    50633    0.038    0.000    0.048    0.000 <frozen importlib._bootstrap>:404(parent)
      804    0.046    0.000    0.048    0.000 ChangeCounter.ipynb:145(update_changes)
   140702    0.047    0.000    0.047    0.000 {method 'write' of '_io.BufferedWriter' objects}
    25316    0.040    0.000    0.047    0.000 symbolic.py:439(to_full_path)
    89938    0.047    0.000    0.047    0.000 cmd.py:517(__init__)
     2448    0.045    0.000    0.046    0.000 threading.py:236(__init__)
   168476    0.046    0.000    0.046    0.000 {method 'split' of 'bytes' objects}
    50633    0.036    0.000    0.045    0.000 <frozen importlib._bootstrap>:1053(_handle_fromlist)
   147608    0.030    0.000    0.045    0.000 posixpath.py:41(_get_sep)
     1271    0.000    0.000    0.044    0.000 git.py:110(get_list_commits)
   185274    0.023    0.000    0.044    0.000 os.py:758(decode)
   181060    0.044    0.000    0.044    0.000 {built-in method __new__ of type object at 0x104e9b0a0}
     1265    0.006    0.000    0.042    0.000 subprocess.py:1893(_try_wait)
   245756    0.042    0.000    0.042    0.000 {built-in method binascii.a2b_hex}
    37976    0.031    0.000    0.039    0.000 head.py:38(__init__)
    27856    0.038    0.000    0.038    0.000 util.py:110(utctz_to_altz)
    25316    0.027    0.000    0.037    0.000 configparser.py:878(has_option)
       86    0.001    0.000    0.036    0.000 cmd.py:1273(clear_cache)
     1353    0.036    0.000    0.036    0.000 {built-in method posix.waitpid}
    91196    0.036    0.000    0.036    0.000 typing.py:1408(_no_init_or_replace_init)
    37213    0.021    0.000    0.034    0.000 base.py:105(__ne__)
    32308    0.019    0.000    0.034    0.000 pathlib.py:619(__str__)
    51748    0.032    0.000    0.034    0.000 config.py:183(add)
     1269    0.033    0.000    0.033    0.000 warnings.py:458(__enter__)
    50632    0.021    0.000    0.033    0.000 base.py:35(__new__)
   145700    0.032    0.000    0.032    0.000 {built-in method binascii.b2a_hex}
   135253    0.032    0.000    0.032    0.000 {method 'startswith' of 'bytes' objects}
      804    0.032    0.000    0.032    0.000 ChangeCounter.ipynb:137(update_size)
   141176    0.031    0.000    0.031    0.000 {method 'group' of 're.Match' objects}
    92730    0.020    0.000    0.031    0.000 os.py:754(encode)
    89938    0.031    0.000    0.031    0.000 base.py:132(__init__)
     1271    0.001    0.000    0.030    0.000 commit.py:318(_iter_from_process_or_stream)
    63808    0.029    0.000    0.029    0.000 {built-in method builtins.setattr}
   128457    0.024    0.000    0.029    0.000 {built-in method builtins.hasattr}
    21273    0.028    0.000    0.028    0.000 {method 'get' of 'dict' objects}
   101449    0.027    0.000    0.027    0.000 {built-in method _codecs.utf_8_decode}
     1269    0.010    0.000    0.026    0.000 subprocess.py:1583(_get_handles)
     2586    0.023    0.000    0.026    0.000 contextlib.py:446(_create_cb_wrapper)
    12542    0.017    0.000    0.025    0.000 config.py:352(__del__)
    25953    0.019    0.000    0.025    0.000 diff.py:403(a_path)
   395830    0.025    0.000    0.025    0.000 {built-in method posix.fspath}
   101449    0.024    0.000    0.024    0.000 codecs.py:260(__init__)
    25410    0.022    0.000    0.024    0.000 configparser.py:644(sections)
      868    0.009    0.000    0.024    0.000 ipkernel.py:790(<setcomp>)
     1220    0.024    0.000    0.024    0.000 {method 'finditer' of 're.Pattern' objects}
    89938    0.024    0.000    0.024    0.000 cmd.py:604(__del__)
     2442    0.016    0.000    0.023    0.000 _weakrefset.py:86(add)
   271034    0.023    0.000    0.023    0.000 {method 'strip' of 'str' objects}
    14740    0.022    0.000    0.022    0.000 util.py:147(__init__)
       84    0.000    0.000    0.022    0.000 base.py:240(__del__)
  370/186    0.001    0.000    0.022    0.000 fun.py:85(find_submodule_git_dir)
       84    0.001    0.000    0.022    0.000 base.py:246(close)
    69182    0.022    0.000    0.022    0.000 {method 'groups' of 're.Match' objects}
     6158    0.022    0.000    0.022    0.000 {built-in method _thread.allocate_lock}
    50725    0.021    0.000    0.021    0.000 __init__.py:966(__init__)
     1269    0.020    0.000    0.020    0.000 contextlib.py:452(__init__)
     2440    0.020    0.000    0.020    0.000 threading.py:775(_newname)
        2    0.000    0.000    0.020    0.010 {built-in method builtins.next}
        2    0.000    0.000    0.020    0.010 repository.py:173(_prep_repo)
    13470    0.015    0.000    0.020    0.000 commit.py:549(committer)
     1269    0.011    0.000    0.019    0.000 warnings.py:165(simplefilter)
   153381    0.019    0.000    0.019    0.000 {method 'rstrip' of 'str' objects}
11032/1269    0.010    0.000    0.019    0.000 cmd.py:1069(__unpack_args)
     2442    0.019    0.000    0.019    0.000 threading.py:1294(_make_invoke_excepthook)
     3855    0.019    0.000    0.019    0.000 {built-in method posix.pipe}
    50725    0.019    0.000    0.019    0.000 base.py:296(common_dir)
    12350    0.009    0.000    0.019    0.000 parse.py:155(password)
    11926    0.012    0.000    0.017    0.000 diff.py:426(renamed_file)
        1    0.000    0.000    0.017    0.017 contextlib.py:139(__exit__)
        2    0.000    0.000    0.016    0.008 git.py:77(clear)
    25316    0.014    0.000    0.016    0.000 util.py:34(sm_name)
     5125    0.016    0.000    0.016    0.000 {built-in method posix.close}
    50632    0.015    0.000    0.015    0.000 base.py:38(__init__)
     7837    0.015    0.000    0.015    0.000 threading.py:1138(ident)
    12986    0.008    0.000    0.014    0.000 pathlib.py:606(_format_parsed_parts)
    26365    0.011    0.000    0.014    0.000 diff.py:407(b_path)
     1265    0.013    0.000    0.014    0.000 subprocess.py:1060(__del__)
        1    0.000    0.000    0.013    0.013 base.py:560(iter_commits)
        1    0.000    0.000    0.013    0.013 commit.py:246(iter_items)
      109    0.000    0.000    0.013    0.000 parse.py:88(clear_cache)
    12658    0.011    0.000    0.013    0.000 util.py:970(__new__)
   195719    0.013    0.000    0.013    0.000 typing.py:1715(cast)
      218    0.012    0.000    0.012    0.000 {method 'clear' of 'dict' objects}
     2722    0.007    0.000    0.012    0.000 posixpath.py:150(dirname)
       93    0.000    0.000    0.012    0.000 base.py:488(config_reader)
     1270    0.006    0.000    0.012    0.000 conf.py:257(is_commit_filtered)
    25640    0.012    0.000    0.012    0.000 {method 'sub' of 're.Pattern' objects}
    25644    0.012    0.000    0.012    0.000 pathlib.py:239(splitroot)
     4884    0.011    0.000    0.012    0.000 threading.py:1423(current_thread)
    62983    0.011    0.000    0.011    0.000 {method 'rpartition' of 'str' objects}
      868    0.011    0.000    0.011    0.000 threading.py:1471(enumerate)
     1269    0.011    0.000    0.011    0.000 {built-in method posix.access}
   126944    0.011    0.000    0.011    0.000 {function _OMD.__getitem__ at 0x14dbb9ea0}
     1269    0.011    0.000    0.011    0.000 warnings.py:437(__init__)
     1270    0.006    0.000    0.010    0.000 commit.py:529(hash)
     1320    0.009    0.000    0.010    0.000 commit.py:623(parents)
   127790    0.010    0.000    0.010    0.000 config.py:387(optionxform)
    12350    0.009    0.000    0.010    0.000 parse.py:189(_userinfo)
    13470    0.008    0.000    0.009    0.000 commit.py:614(msg)
      463    0.002    0.000    0.009    0.000 fun.py:44(is_git_dir)
    27856    0.009    0.000    0.009    0.000 util.py:646(__init__)
    37976    0.009    0.000    0.009    0.000 symbolic.py:65(__init__)
     2440    0.006    0.000    0.009    0.000 threading.py:1191(daemon)
     1269    0.005    0.000    0.008    0.000 warnings.py:181(_add_filter)
     2442    0.006    0.000    0.008    0.000 threading.py:1021(_stop)
    12543    0.005    0.000    0.008    0.000 config.py:364(release)
    12752    0.007    0.000    0.008    0.000 config.py:333(_acquire_lock)
    50632    0.008    0.000    0.008    0.000 base.py:52(type)
    70327    0.008    0.000    0.008    0.000 {method 'readline' of '_io.BytesIO' objects}
   101264    0.008    0.000    0.008    0.000 {built-in method builtins.ord}
    77602    0.008    0.000    0.008    0.000 {method 'lower' of 'str' objects}
    12658    0.007    0.000    0.007    0.000 fun.py:180(to_commit)
    12658    0.007    0.000    0.007    0.000 util.py:973(__init__)
    12752    0.006    0.000    0.007    0.000 configparser.py:1363(__iter__)
     5130    0.005    0.000    0.007    0.000 base.py:123(hexsha)
      279    0.003    0.000    0.007    0.000 util.py:400(expand_path)
    12350    0.006    0.000    0.007    0.000 parse.py:114(_coerce_args)
     2442    0.006    0.000    0.007    0.000 _weakrefset.py:39(_remove)
     2530    0.005    0.000    0.007    0.000 subprocess.py:1173(poll)
     1362    0.001    0.000    0.007    0.000 abc.py:117(__instancecheck__)
    50632    0.007    0.000    0.007    0.000 base.py:42(binsha)
     1269    0.005    0.000    0.006    0.000 _collections_abc.py:828(keys)
     1271    0.004    0.000    0.006    0.000 __init__.py:1467(info)
     2440    0.005    0.000    0.006    0.000 base.py:115(__str__)
     7654    0.005    0.000    0.006    0.000 conf.py:45(get)
    13918    0.006    0.000    0.006    0.000 {method 'join' of 'str' objects}
     2456    0.005    0.000    0.006    0.000 threading.py:264(__enter__)
    12658    0.004    0.000    0.006    0.000 base.py:99(__eq__)
     1269    0.006    0.000    0.006    0.000 cmd.py:416(__init__)
     1304    0.005    0.000    0.005    0.000 {built-in method posix.stat}
     4884    0.005    0.000    0.005    0.000 threading.py:1176(daemon)
     3713    0.005    0.000    0.005    0.000 {method 'add' of 'set' objects}
    75506    0.005    0.000    0.005    0.000 {method 'replace' of 'str' objects}
     1362    0.005    0.000    0.005    0.000 {built-in method _abc._abc_instancecheck}
    50632    0.005    0.000    0.005    0.000 base.py:60(size)
     2443    0.004    0.000    0.005    0.000 threading.py:276(_acquire_restore)
    25408    0.005    0.000    0.005    0.000 util.py:194(to_native_path_linux)
     2440    0.005    0.000    0.005    0.000 threading.py:1162(is_alive)
      928    0.001    0.000    0.005    0.000 genericpath.py:39(isdir)
    14740    0.005    0.000    0.005    0.000 developer.py:27(__init__)
     2443    0.003    0.000    0.004    0.000 threading.py:279(_is_owned)
    12750    0.004    0.000    0.004    0.000 base.py:309(bare)
    25500    0.004    0.000    0.004    0.000 base.py:290(working_tree_dir)
    50725    0.004    0.000    0.004    0.000 configparser.py:363(before_get)
      931    0.003    0.000    0.004    0.000 posixpath.py:337(normpath)
    63760    0.004    0.000    0.004    0.000 {built-in method builtins.callable}
     2586    0.001    0.000    0.004    0.000 contextlib.py:448(_exit_wrapper)
    58960    0.004    0.000    0.004    0.000 util.py:160(dst)
        1    0.001    0.001    0.004    0.004 _base.py:636(__exit__)
     1273    0.003    0.000    0.003    0.000 {method 'remove' of 'list' objects}
     7324    0.003    0.000    0.003    0.000 threading.py:546(is_set)
    11926    0.003    0.000    0.003    0.000 diff.py:411(rename_from)
    45490    0.003    0.000    0.003    0.000 util.py:154(utcoffset)
        1    0.000    0.000    0.003    0.003 contextlib.py:130(__enter__)
    29187    0.003    0.000    0.003    0.000 {method 'endswith' of 'bytes' objects}
     2441    0.002    0.000    0.003    0.000 encoding.py:1(force_bytes)
        1    0.000    0.000    0.003    0.003 thread.py:216(shutdown)
       93    0.001    0.000    0.003    0.000 db.py:37(__init__)
     2540    0.003    0.000    0.003    0.000 __init__.py:1724(isEnabledFor)
    25410    0.003    0.000    0.003    0.000 {method 'keys' of 'collections.OrderedDict' objects}
    12546    0.003    0.000    0.003    0.000 config.py:707(read_only)
     1269    0.003    0.000    0.003    0.000 cmd.py:1148(<dictcomp>)
    12752    0.003    0.000    0.003    0.000 configparser.py:1191(converters)
     1269    0.003    0.000    0.003    0.000 {built-in method sys.exc_info}
        1    0.000    0.000    0.002    0.002 git.py:39(__init__)
     1319    0.001    0.000    0.002    0.000 cmd.py:180(dashify)
        1    0.000    0.000    0.002    0.002 git.py:86(_open_repository)
       93    0.000    0.000    0.002    0.000 configparser.py:827(getboolean)
      281    0.001    0.000    0.002    0.000 posixpath.py:376(abspath)
    15255    0.002    0.000    0.002    0.000 {method 'strip' of 'bytes' objects}
     1453    0.002    0.000    0.002    0.000 {method 'rfind' of 'str' objects}
       93    0.001    0.000    0.002    0.000 configparser.py:806(_get_conv)
     1269    0.001    0.000    0.002    0.000 __init__.py:1455(debug)
     3795    0.002    0.000    0.002    0.000 subprocess.py:1858(_internal_poll)
    11926    0.002    0.000    0.002    0.000 diff.py:415(rename_to)
     1270    0.002    0.000    0.002    0.000 {built-in method builtins.sorted}
     2441    0.002    0.000    0.002    0.000 cmd.py:632(__getattr__)
     1220    0.002    0.000    0.002    0.000 base.py:90(_set_cache_)
    13470    0.002    0.000    0.002    0.000 {method 'end' of 're.Match' objects}
     1265    0.001    0.000    0.002    0.000 subprocess.py:1846(_handle_exitstatus)
    25645    0.002    0.000    0.002    0.000 {method 'reverse' of 'list' objects}
     2530    0.002    0.000    0.002    0.000 {method 'close' of '_io.BufferedReader' objects}
     2456    0.001    0.000    0.002    0.000 threading.py:267(__exit__)
    13928    0.002    0.000    0.002    0.000 {method 'read' of '_io.BytesIO' objects}
       93    0.000    0.000    0.002    0.000 configparser.py:803(_get)
    13216    0.002    0.000    0.002    0.000 {method 'pop' of 'list' objects}
       93    0.001    0.000    0.002    0.000 loose.py:77(__init__)
     1270    0.001    0.000    0.001    0.000 commit.py:538(author)
     2188    0.001    0.000    0.001    0.000 <string>:1(<lambda>)
       44    0.000    0.000    0.001    0.000 subprocess.py:2093(terminate)
       93    0.000    0.000    0.001    0.000 cmd.py:612(__init__)
       44    0.000    0.000    0.001    0.000 subprocess.py:2061(send_signal)
       93    0.000    0.000    0.001    0.000 re.py:197(search)
    12752    0.001    0.000    0.001    0.000 {built-in method builtins.iter}
     2443    0.001    0.000    0.001    0.000 threading.py:273(_release_save)
       44    0.001    0.000    0.001    0.000 {method 'close' of '_io.BufferedWriter' objects}
     1269    0.001    0.000    0.001    0.000 warnings.py:477(__exit__)
       93    0.000    0.000    0.001    0.000 genericpath.py:16(exists)
     7326    0.001    0.000    0.001    0.000 {built-in method _thread.get_ident}
    12250    0.001    0.000    0.001    0.000 {method 'start' of 're.Match' objects}
     1269    0.001    0.000    0.001    0.000 subprocess.py:246(_cleanup)
       93    0.001    0.000    0.001    0.000 _collections_abc.py:820(__contains__)
       93    0.001    0.000    0.001    0.000 re.py:288(_compile)
     1269    0.001    0.000    0.001    0.000 _collections_abc.py:854(__init__)
    12350    0.001    0.000    0.001    0.000 parse.py:103(_noop)
        5    0.001    0.000    0.001    0.000 {method 'put' of '_queue.SimpleQueue' objects}
       44    0.001    0.000    0.001    0.000 {built-in method posix.kill}
     1269    0.001    0.000    0.001    0.000 cmd.py:1058(transform_kwargs)
      281    0.000    0.000    0.001    0.000 genericpath.py:27(isfile)
     2188    0.001    0.000    0.001    0.000 {method 'find' of 'str' objects}
       93    0.000    0.000    0.001    0.000 base.py:113(__init__)
     1269    0.001    0.000    0.001    0.000 cmd.py:1156(<listcomp>)
        3    0.000    0.000    0.001    0.000 config.py:659(write)
     2442    0.001    0.000    0.001    0.000 {method 'discard' of 'set' objects}
     1269    0.001    0.000    0.001    0.000 {method 'rfind' of 'bytes' objects}
      2/1    0.000    0.000    0.001    0.001 config.py:117(flush_changes)
     4973    0.001    0.000    0.001    0.000 {method 'release' of '_thread.lock' objects}
        2    0.000    0.000    0.001    0.000 pathlib.py:1062(resolve)
     3318    0.001    0.000    0.001    0.000 {method '__exit__' of '_thread.RLock' objects}
        1    0.000    0.000    0.001    0.001 repository.py:240(<dictcomp>)
        4    0.000    0.000    0.001    0.000 thread.py:161(submit)
        1    0.000    0.000    0.001    0.001 base.py:511(config_writer)
       94    0.000    0.000    0.001    0.000 base.py:464(_get_config_path)
        2    0.000    0.000    0.001    0.000 posixpath.py:391(realpath)
     1270    0.000    0.000    0.001    0.000 git.py:134(get_commit_from_gitpython)
     2448    0.001    0.000    0.001    0.000 {method '__enter__' of '_thread.lock' objects}
        2    0.000    0.000    0.001    0.000 posixpath.py:400(_joinrealpath)
        4    0.000    0.000    0.001    0.000 thread.py:180(_adjust_thread_count)
       84    0.000    0.000    0.001    0.000 mman.py:408(collect)
        4    0.000    0.000    0.001    0.000 util.py:878(_obtain_lock)
        4    0.000    0.000    0.001    0.000 util.py:856(_obtain_lock_or_raise)
     4929    0.001    0.000    0.001    0.000 {method 'insert' of 'list' objects}
        8    0.001    0.000    0.001    0.000 {built-in method posix.lstat}
        5    0.000    0.000    0.001    0.000 _base.py:201(as_completed)
      279    0.000    0.000    0.001    0.000 posixpath.py:228(expanduser)
     1269    0.001    0.000    0.001    0.000 cmd.py:1149(<dictcomp>)
        1    0.001    0.001    0.001    0.001 {built-in method posix.open}
        1    0.000    0.000    0.001    0.001 config.py:791(set_value)
      467    0.000    0.000    0.000    0.000 posixpath.py:60(isabs)
       84    0.000    0.000    0.000    0.000 mman.py:303(_collect_lru_region)
       93    0.000    0.000    0.000    0.000 base.py:70(__init__)
     3725    0.000    0.000    0.000    0.000 {method '__exit__' of '_thread.lock' objects}
     5077    0.000    0.000    0.000    0.000 {method 'items' of 'dict' objects}
     3807    0.000    0.000    0.000    0.000 {built-in method _warnings._filters_mutated}
       93    0.000    0.000    0.000    0.000 configparser.py:1163(_convert_to_boolean)
     2188    0.000    0.000    0.000    0.000 parse.py:419(_checknetloc)
        1    0.000    0.000    0.000    0.000 repository.py:256(_split_in_chunks)
       92    0.000    0.000    0.000    0.000 base.py:197(abspath)
     3472    0.000    0.000    0.000    0.000 {method 'keys' of 'dict' objects}
     1269    0.000    0.000    0.000    0.000 {built-in method sys.audit}
        1    0.000    0.000    0.000    0.000 {built-in method math.ceil}
     1265    0.000    0.000    0.000    0.000 {built-in method posix.WIFSTOPPED}
        3    0.000    0.000    0.000    0.000 config.py:615(_write)
     2586    0.000    0.000    0.000    0.000 {method 'pop' of 'collections.deque' objects}
     1270    0.000    0.000    0.000    0.000 commit.py:503(__init__)
       45    0.000    0.000    0.000    0.000 config.py:618(write_section)
     1317    0.000    0.000    0.000    0.000 {method 'update' of 'dict' objects}
        2    0.000    0.000    0.000    0.000 weakref.py:370(remove)
        1    0.000    0.000    0.000    0.000 _base.py:157(_create_and_install_waiters)
        1    0.000    0.000    0.000    0.000 _base.py:79(__init__)
        1    0.000    0.000    0.000    0.000 _base.py:63(__init__)
     1269    0.000    0.000    0.000    0.000 contextlib.py:530(__enter__)
     1820    0.000    0.000    0.000    0.000 {method 'values' of 'dict' objects}
     1265    0.000    0.000    0.000    0.000 {built-in method posix.waitstatus_to_exitcode}
       52    0.000    0.000    0.000    0.000 cmd.py:1042(transform_kwarg)
     1220    0.000    0.000    0.000    0.000 util.py:257(_set_cache_)
      277    0.000    0.000    0.000    0.000 cmd.py:368(is_cygwin)
      279    0.000    0.000    0.000    0.000 posixpath.py:284(expandvars)
     1220    0.000    0.000    0.000    0.000 diff.py:86(_process_diff_args)
     1269    0.000    0.000    0.000    0.000 {method 'pop' of 'dict' objects}
     2446    0.000    0.000    0.000    0.000 {method 'locked' of '_thread.lock' objects}
        6    0.000    0.000    0.000    0.000 _base.py:179(_yield_finished_futures)
       92    0.000    0.000    0.000    0.000 base.py:266(__ne__)
      804    0.000    0.000    0.000    0.000 ChangeCounter.ipynb:155(update_elems)
        1    0.000    0.000    0.000    0.000 git.py:92(_discover_main_branch)
        1    0.000    0.000    0.000    0.000 base.py:792(active_branch)
        1    0.000    0.000    0.000    0.000 symbolic.py:288(_get_reference)
        1    0.000    0.000    0.000    0.000 thread.py:123(__init__)
       45    0.000    0.000    0.000    0.000 config.py:216(items_all)
      835    0.000    0.000    0.000    0.000 {built-in method _stat.S_ISDIR}
       45    0.000    0.000    0.000    0.000 config.py:218(<listcomp>)
       92    0.000    0.000    0.000    0.000 base.py:261(__eq__)
        2    0.000    0.000    0.000    0.000 util.py:883(_release_lock)
        4    0.000    0.000    0.000    0.000 threading.py:421(acquire)
      277    0.000    0.000    0.000    0.000 util.py:347(is_cygwin_git)
       88    0.000    0.000    0.000    0.000 config.py:786(_value_to_string)
        1    0.000    0.000    0.000    0.000 util.py:139(rmfile)
        1    0.000    0.000    0.000    0.000 conf.py:77(sanity_check_filters)
        4    0.000    0.000    0.000    0.000 _base.py:418(result)
        1    0.000    0.000    0.000    0.000 {built-in method posix.remove}
      132    0.000    0.000    0.000    0.000 config.py:209(getall)
        1    0.000    0.000    0.000    0.000 conf.py:287(_check_timezones)
        1    0.000    0.000    0.000    0.000 repository.py:44(__init__)
        1    0.000    0.000    0.000    0.000 conf.py:293(_replace_timezone)
        3    0.000    0.000    0.000    0.000 config.py:212(items)
        1    0.000    0.000    0.000    0.000 threading.py:415(__init__)
        3    0.000    0.000    0.000    0.000 config.py:214(<listcomp>)
        1    0.000    0.000    0.000    0.000 symbolic.py:685(from_path)
        4    0.000    0.000    0.000    0.000 _base.py:318(__init__)
      187    0.000    0.000    0.000    0.000 {built-in method _stat.S_ISREG}
        2    0.000    0.000    0.000    0.000 pathlib.py:1090(stat)
        1    0.000    0.000    0.000    0.000 conf.py:24(__init__)
       57    0.000    0.000    0.000    0.000 {method 'find' of 'bytes' objects}
        2    0.000    0.000    0.000    0.000 threading.py:793(_maintain_shutdown_locks)
        2    0.000    0.000    0.000    0.000 repository.py:148(_is_remote)
       88    0.000    0.000    0.000    0.000 encoding.py:11(force_text)
        7    0.000    0.000    0.000    0.000 conf.py:36(set_value)
        4    0.000    0.000    0.000    0.000 pathlib.py:629(__fspath__)
        1    0.000    0.000    0.000    0.000 conf.py:191(build_args)
        1    0.000    0.000    0.000    0.000 threading.py:572(clear)
       57    0.000    0.000    0.000    0.000 {method 'rstrip' of 'bytes' objects}
        1    0.000    0.000    0.000    0.000 {method 'replace' of 'datetime.datetime' objects}
        1    0.000    0.000    0.000    0.000 git.py:322(__del__)
        5    0.000    0.000    0.000    0.000 {method 'remove' of 'set' objects}
        1    0.000    0.000    0.000    0.000 _base.py:146(__init__)
        4    0.000    0.000    0.000    0.000 _base.py:388(__get_result)
       93    0.000    0.000    0.000    0.000 {built-in method builtins.issubclass}
        8    0.000    0.000    0.000    0.000 {method '__enter__' of '_thread.RLock' objects}
        2    0.000    0.000    0.000    0.000 weakref.py:428(__setitem__)
        4    0.000    0.000    0.000    0.000 threading.py:90(RLock)
        4    0.000    0.000    0.000    0.000 thread.py:47(__init__)
        1    0.000    0.000    0.000    0.000 _base.py:149(__enter__)
        1    0.000    0.000    0.000    0.000 configparser.py:892(set)
        1    0.000    0.000    0.000    0.000 reference.py:46(__init__)
        1    0.000    0.000    0.000    0.000 conf.py:65(_check_only_one_from_commit)
        1    0.000    0.000    0.000    0.000 contextlib.py:279(helper)
        1    0.000    0.000    0.000    0.000 _base.py:153(__exit__)
        2    0.000    0.000    0.000    0.000 conf.py:181(only_one_filter)
        1    0.000    0.000    0.000    0.000 contextlib.py:102(__init__)
        1    0.000    0.000    0.000    0.000 conf.py:71(_check_only_one_to_commit)
        8    0.000    0.000    0.000    0.000 {method 'partition' of 'str' objects}
        2    0.000    0.000    0.000    0.000 threading.py:803(<listcomp>)
        1    0.000    0.000    0.000    0.000 util.py:844(__del__)
        8    0.000    0.000    0.000    0.000 util.py:851(_has_lock)
        3    0.000    0.000    0.000    0.000 config.py:699(_assure_writable)
        1    0.000    0.000    0.000    0.000 reference.py:100(name)
        2    0.000    0.000    0.000    0.000 util.py:847(_lock_file_path)
        3    0.000    0.000    0.000    0.000 git.py:63(repo)
        4    0.000    0.000    0.000    0.000 _base.py:225(<genexpr>)
        1    0.000    0.000    0.000    0.000 conf.py:54(_sanity_check_repos)
        2    0.000    0.000    0.000    0.000 {method 'difference_update' of 'set' objects}
        1    0.000    0.000    0.000    0.000 conf.py:142(get_starting_commit)
        4    0.000    0.000    0.000    0.000 {method 'lstrip' of 'str' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 conf.py:114(_check_correct_filters_order)
        8    0.000    0.000    0.000    0.000 {built-in method _stat.S_ISLNK}
        1    0.000    0.000    0.000    0.000 pathlib.py:708(name)
        1    0.000    0.000    0.000    0.000 conf.py:165(get_ending_commit)
        2    0.000    0.000    0.000    0.000 conf.py:189(<listcomp>)
        2    0.000    0.000    0.000    0.000 {method 'remove' of 'collections.deque' objects}
        4    0.000    0.000    0.000    0.000 {built-in method time.monotonic}
        2    0.000    0.000    0.000    0.000 pathlib.py:1430(expanduser)
        4    0.000    0.000    0.000    0.000 {method 'release' of '_thread.RLock' objects}
        4    0.000    0.000    0.000    0.000 {method 'acquire' of '_thread.RLock' objects}
        1    0.000    0.000    0.000    0.000 __init__.py:230(utcoffset)
        1    0.000    0.000    0.000    0.000 configparser.py:663(has_section)
        1    0.000    0.000    0.000    0.000 util.py:840(__init__)
        1    0.000    0.000    0.000    0.000 _base.py:633(__enter__)
        1    0.000    0.000    0.000    0.000 configparser.py:366(before_set)

Yes, that's an awful lot of functions, but we can quickly narrow things down. The cumtime column is sorted by largest values first. We see that the debuggingbook_change_counter() method at the top takes up all the time – but this is not surprising, since it is the method we called in the first place. This calls a method mine() in the ChangeCounter class, which does all the work.

The next places are more interesting: almost all time is spent in a single method, named modifications(). This method determines the difference between two versions, which is an expensive operation; this is also supported by the observation that half of the time is spent in a diff() method.

This profile thus already gets us a hint on how to improve performance: Rather than computing the diff between versions for every version, we could do so on demand (and possibly cache results so we don't have to compute them twice). Alas, this (slow) functionality is part of the underlying PyDriller Python package, so we cannot fix this within the ChangeCounter class. But we could file a bug with the developers, suggesting a patch to improve performance.

Sampling Execution Profiles

Instrumenting code is precise, but it is also slow. An alternate way to measure performance is to sample in regular intervals which functions are currently active – for instance, by examining the current function call stack. The more frequently a function is sampled as active, the more time is spent in that function.

One profiler for Python that implements such sampling is Scalene – a high-performance, high-precision CPU, GPU, and memory profiler for Python. We can invoke it on our example as follows:

$ scalene --html test.py > scalene-out.html

where test.py is a script that again invokes

debuggingbook_change_counter(ChangeCounter)

The output of scalene is sent to a HTML file (here, scalene-out.html) which is organized by lines – that is, for each line, we see how much it contributed to overall execution time. Opening the output scalene-out.html in a HTML browser, we see these lines:

As with cProfile, above, we identify the mine() method in the ChangeCounter class as the main performance hog – and in the mine() method, it is the iteration over all modifications that takes all the time. Adding the option --profile-all to scalene would extend the profile to all executed code, including the pydriller third-party library.

Besides relying on sampling rather that tracing (which is more efficient) and breaking down execution time by line, scalene also provides additional information on memory usage and more. If cProfile is not sufficient, then scalene will bring profiling to the next level.

Improving Performance

Identifying a culprit is not always that easy. Notably, when the first set of obvious performance hogs is fixed, it becomes more and more difficult to squeeze out additional performance – and, as stated above, such optimization may be in conflict with readability and maintainability of your code. Here are some simple ways to improve performance:

  • Efficient algorithms. For many tasks, the simplest algorithm is not always the best performing one. Consider alternatives that may be more efficient, and measure whether they pay off.

  • Efficient data types. Remember that certain operations, such as looking up whether an element is contained, may take different amounts of time depending on the data structure. In Python, a query like x in xs takes (mostly) constant time if xs is a set, but linear time if xs is a list; these differences become significant as the size of xs grows.

  • Efficient modules. In Python, most frequently used modules (or at least parts of) are implemented in C, which is way more efficient than plain Python. Rely on existing modules whenever possible. Or implement your own, after having measured that this may pay off.

These are all things you can already use during programming – and also set up your code such that exchanging, say, one data type by another will still be possible later. This is best achieved by hiding implementation details (such as the used data types) behind an abstract interface used by your clients.

But beyond these points, remember the famous words by Donald E. Knuth:

from bookutils import quiz

Quiz

Donald E. Knuth said: "Premature optimization..."





This quote should always remind us that after a good design, you should always first measure and then optimize.

Building a Profiler

Having discussed profilers from a user perspective, let us now dive into how they are actually implemented. It turns out we can use most of our existing infrastructure to implement a simple tracing profiler with only a few lines of code.

The program we will apply our profiler on is – surprise! – our ongoing example, remove_html_markup(). Our aim is to understand how much time is spent in each line of the code (such that we have a new feature on top of Python cProfile).

from Intro_Debugging import remove_html_markup
print_content(inspect.getsource(remove_html_markup), '.py',
              start_line_number=238)
238  def remove_html_markup(s):  # type: ignore
239      tag = False
240      quote = False
241      out = ""
242  
243      for c in s:
244          assert tag or not quote
245  
246          if c == '<' and not quote:
247              tag = True
248          elif c == '>' and not quote:
249              tag = False
250          elif (c == '"' or c == "'") and tag:
251              quote = not quote
252          elif not tag:
253              out = out + c
254  
255      return out

We introduce a class PerformanceTracer that tracks, for each line in the code:

  • how often it was executed (hits), and
  • how much time was spent during its execution (time).

To this end, we make use of our Timer class, which measures time, and the Tracer class from the chapter on tracing, which allows us to track every line of the program as it is being executed.

from Tracer import Tracer

In PerformanceTracker, the attributes hits and time are mappings indexed by unique locations – that is, pairs of function name and line number.

Location = Tuple[str, int]
class PerformanceTracer(Tracer):
    """Trace time and #hits for individual program lines"""

    def __init__(self) -> None:
        """Constructor."""
        super().__init__()
        self.reset_timer()
        self.hits: Dict[Location, int] = {}
        self.time: Dict[Location, float] = {}

    def reset_timer(self) -> None:
        self.timer = Timer.Timer()

As common in this book, we want to use PerformanceTracer in a with-block around the function call(s) to be tracked:

with PerformanceTracer() as perf_tracer:
    function(...)

When entering the with block (__enter__()), we reset all timers. Also, coming from the __enter__() method of the superclass Tracer, we enable tracing through the traceit() method.

from types import FrameType
class PerformanceTracer(PerformanceTracer):
    def __enter__(self) -> Any:
        """Enter a `with` block."""
        super().__enter__()
        self.reset_timer()
        return self

The traceit() method extracts the current location. It increases the corresponding hits value by 1, and adds the elapsed time to the corresponding time.

class PerformanceTracer(PerformanceTracer):
    def traceit(self, frame: FrameType, event: str, arg: Any) -> None:
        """Tracing function; called for every line."""
        t = self.timer.elapsed_time()
        location = (frame.f_code.co_name, frame.f_lineno)

        self.hits.setdefault(location, 0)
        self.time.setdefault(location, 0.0)
        self.hits[location] += 1
        self.time[location] += t

        self.reset_timer()

This is it already. We can now determine where most time is spent in remove_html_markup(). We invoke it 10,000 times such that we can average over runs:

with PerformanceTracer() as perf_tracer:
    for i in range(10000):
        s = remove_html_markup('<b>foo</b>')

Here are the hits. For every line executed, we see how often it was executed. The most executed line is the for loop with 110,000 hits – once for each of the 10 characters in <b>foo</b>, once for the final check, and all of this 10,000 times.

perf_tracer.hits
{('__init__', 17): 1,
 ('__init__', 19): 1,
 ('clock', 8): 1,
 ('clock', 12): 2,
 ('__init__', 20): 2,
 ('remove_html_markup', 238): 10000,
 ('remove_html_markup', 239): 10000,
 ('remove_html_markup', 240): 10000,
 ('remove_html_markup', 241): 10000,
 ('remove_html_markup', 243): 110000,
 ('remove_html_markup', 244): 100000,
 ('remove_html_markup', 246): 100000,
 ('remove_html_markup', 247): 20000,
 ('remove_html_markup', 248): 80000,
 ('remove_html_markup', 250): 60000,
 ('remove_html_markup', 252): 60000,
 ('remove_html_markup', 249): 20000,
 ('remove_html_markup', 253): 30000,
 ('remove_html_markup', 255): 20000}

The time attribute collects how much time was spent in each line. Within the loop, again, the for statement takes the most time. The other lines show some variability, though.

perf_tracer.time
{('__init__', 17): 2.4874985683709383e-05,
 ('__init__', 19): 1.6669509932398796e-06,
 ('clock', 8): 1.1249794624745846e-06,
 ('clock', 12): 1.7499551177024841e-06,
 ('__init__', 20): 1.9579892978072166e-06,
 ('remove_html_markup', 238): 0.012263340235222131,
 ('remove_html_markup', 239): 0.011493229889310896,
 ('remove_html_markup', 240): 0.010979408340062946,
 ('remove_html_markup', 241): 0.010019488167017698,
 ('remove_html_markup', 243): 0.09736047266051173,
 ('remove_html_markup', 244): 0.0865233785007149,
 ('remove_html_markup', 246): 0.08576506655663252,
 ('remove_html_markup', 247): 0.01743341883411631,
 ('remove_html_markup', 248): 0.0691332631977275,
 ('remove_html_markup', 250): 0.05126661161193624,
 ('remove_html_markup', 252): 0.05368070403346792,
 ('remove_html_markup', 249): 0.017349720059428364,
 ('remove_html_markup', 253): 0.02558118914021179,
 ('remove_html_markup', 255): 0.017243082402274013}

For a full profiler, these numbers would now be sorted and printed in a table, much like cProfile does. However, we will borrow some material from previous chapters and annotate our code accordingly.

Visualizing Performance Metrics

In the chapter on statistical debugging, we have encountered the CoverageCollector class, which collects line and function coverage during execution, using a collect() method that is invoked for every line. We will repurpose this class to collect arbitrary metrics on the lines executed, notably time taken.

Collecting Time Spent

from StatisticalDebugger import CoverageCollector, SpectrumDebugger

The MetricCollector class is an abstract superclass that provides an interface to access a particular metric.

class MetricCollector(CoverageCollector):
    """Abstract superclass for collecting line-specific metrics"""

    def metric(self, event: Any) -> Optional[float]:
        """Return a metric for an event, or none."""
        return None

    def all_metrics(self, func: str) -> List[float]:
        """Return all metric for a function `func`."""
        return []

Given these metrics, we can also compute sums and maxima for a single function.

class MetricCollector(MetricCollector):
    def total(self, func: str) -> float:
        return sum(self.all_metrics(func))

    def maximum(self, func: str) -> float:
        return max(self.all_metrics(func))

Let us instantiate this superclass into TimeCollector – a subclass that measures time. This is modeled after our PerformanceTracer class, above; notably, the time attribute serves the same role.

class TimeCollector(MetricCollector):
    """Collect time executed for each line"""

    def __init__(self) -> None:
        """Constructor"""
        super().__init__()
        self.reset_timer()
        self.time: Dict[Location, float] = {}
        self.add_items_to_ignore([Timer.Timer, Timer.clock])

    def collect(self, frame: FrameType, event: str, arg: Any) -> None:
        """Invoked for every line executed. Accumulate time spent."""
        t = self.timer.elapsed_time()
        super().collect(frame, event, arg)
        location = (frame.f_code.co_name, frame.f_lineno)

        self.time.setdefault(location, 0.0)
        self.time[location] += t

        self.reset_timer()

    def reset_timer(self) -> None:
        self.timer = Timer.Timer()

    def __enter__(self) -> Any:
        super().__enter__()
        self.reset_timer()
        return self

The metric() and all_metrics() methods accumulate the metric (time taken) for an individual function:

class TimeCollector(TimeCollector):
    def metric(self, location: Any) -> Optional[float]:
        if location in self.time:
            return self.time[location]
        else:
            return None

    def all_metrics(self, func: str) -> List[float]:
        return [time
                for (func_name, lineno), time in self.time.items()
                if func_name == func]

Here's how to use TimeCollector() – again, in a with block:

with TimeCollector() as collector:
    for i in range(100):
        s = remove_html_markup('<b>foo</b>')

The time attribute holds the time spent in each line:

for location, time_spent in collector.time.items():
    print(location, time_spent)
('remove_html_markup', 238) 0.00022766191978007555
('remove_html_markup', 239) 0.00019945891108363867
('remove_html_markup', 240) 0.0001841600751504302
('remove_html_markup', 241) 0.00016928481636568904
('remove_html_markup', 243) 0.0016425381181761622
('remove_html_markup', 244) 0.0014470171881839633
('remove_html_markup', 246) 0.0015351754263974726
('remove_html_markup', 247) 0.0002907503512687981
('remove_html_markup', 248) 0.0011504249996505678
('remove_html_markup', 250) 0.0008595951367169619
('remove_html_markup', 252) 0.0009983080090023577
('remove_html_markup', 249) 0.00028925150400027633
('remove_html_markup', 253) 0.00042692222632467747
('remove_html_markup', 255) 0.0002905394067056477

And we can also create a total for an entire function:

collector.total('remove_html_markup')
0.009711088088806719

Visualizing Time Spent

Let us now go and visualize these numbers in a simple form. The idea is to assign each line a color whose saturation indicates the time spent in that line relative to the time spent in the function overall – the higher the fraction, the darker the line. We create a MetricDebugger class built as a specialization of SpectrumDebugger, in which suspiciousness() and color() are repurposed to show these metrics.

class MetricDebugger(SpectrumDebugger):
    """Visualize a metric"""

    def metric(self, location: Location) -> float:
        sum = 0.0
        for outcome in self.collectors:
            for collector in self.collectors[outcome]:
                assert isinstance(collector, MetricCollector)
                m = collector.metric(location)
                if m is not None:
                    sum += m

        return sum

    def total(self, func_name: str) -> float:
        total = 0.0
        for outcome in self.collectors:
            for collector in self.collectors[outcome]:
                assert isinstance(collector, MetricCollector)
                total += sum(collector.all_metrics(func_name))

        return total

    def maximum(self, func_name: str) -> float:
        maximum = 0.0
        for outcome in self.collectors:
            for collector in self.collectors[outcome]:
                assert isinstance(collector, MetricCollector)
                maximum = max(maximum, 
                              max(collector.all_metrics(func_name)))

        return maximum

    def suspiciousness(self, location: Location) -> float:
        func_name, _ = location
        return self.metric(location) / self.total(func_name)

    def color(self, location: Location) -> str:
        func_name, _ = location
        hue = 240  # blue
        saturation = 100  # fully saturated
        darkness = self.metric(location) / self.maximum(func_name)
        lightness = 100 - darkness * 25
        return f"hsl({hue}, {saturation}%, {lightness}%)"

    def tooltip(self, location: Location) -> str:
        return f"{super().tooltip(location)} {self.metric(location)}"

We can now introduce PerformanceDebugger as a subclass of MetricDebugger, using an arbitrary MetricCollector (such as TimeCollector) to obtain the metric we want to visualize.

class PerformanceDebugger(MetricDebugger):
    """Collect and visualize a metric"""

    def __init__(self, collector_class: Type, log: bool = False):
        assert issubclass(collector_class, MetricCollector)
        super().__init__(collector_class, log=log)

With PerformanceDebugger, we inherit all the capabilities of SpectrumDebugger, such as showing the (relative) percentage of time spent in a table. We see that the for condition and the following assert take most of the time, followed by the first condition.

with PerformanceDebugger(TimeCollector) as debugger:
    for i in range(100):
        s = remove_html_markup('<b>foo</b>')
print(debugger)
 238   2% def remove_html_markup(s):  # type: ignore
 239   2%     tag = False
 240   1%     quote = False
 241   1%     out = ""
 242   0%
 243  17%     for c in s:
 244  15%         assert tag or not quote
 245   0%
 246  14%         if c == '<' and not quote:
 247   3%             tag = True
 248  11%         elif c == '>' and not quote:
 249   3%             tag = False
 250   8%         elif (c == '"' or c == "'") and tag:
 251   0%             quote = not quote
 252   9%         elif not tag:
 253   4%             out = out + c
 254   0%
 255   3%     return out

However, we can also visualize these percentages, using shades of blue to indicate those lines most time spent in:

debugger
 238 def remove_html_markup(s):  # type: ignore
 239     tag = False
 240     quote = False
 241     out = ""
 242  
 243     for c in s:
 244         assert tag or not quote
 245  
 246         if c == '<' and not quote:
 247             tag = True
 248         elif c == '>' and not quote:
 249             tag = False
 250         elif (c == '"' or c == "'") and tag:
 251             quote = not quote
 252         elif not tag:
 253             out = out + c
 254  
 255     return out

Other Metrics

Our framework is flexible enough to collect (and visualize) arbitrary metrics. This HitCollector class, for instance, collects how often a line is being executed.

class HitCollector(MetricCollector):
    """Collect how often a line is executed"""

    def __init__(self) -> None:
        super().__init__()
        self.hits: Dict[Location, int] = {}

    def collect(self, frame: FrameType, event: str, arg: Any) -> None:
        super().collect(frame, event, arg)
        location = (frame.f_code.co_name, frame.f_lineno)

        self.hits.setdefault(location, 0)
        self.hits[location] += 1

    def metric(self, location: Location) -> Optional[int]:
        if location in self.hits:
            return self.hits[location]
        else:
            return None

    def all_metrics(self, func: str) -> List[float]:
        return [hits
                for (func_name, lineno), hits in self.hits.items()
                if func_name == func]

We can plug in this class into PerformanceDebugger to obtain a distribution of lines executed:

with PerformanceDebugger(HitCollector) as debugger:
    for i in range(100):
        s = remove_html_markup('<b>foo</b>')

In total, during this call to remove_html_markup(), there are 6,400 lines executed:

debugger.total('remove_html_markup')
6400.0

Again, we can visualize the distribution as a table and using colors. We can see how the shade gets lighter in the lower part of the loop as individual conditions have been met.

print(debugger)
 238   1% def remove_html_markup(s):  # type: ignore
 239   1%     tag = False
 240   1%     quote = False
 241   1%     out = ""
 242   0%
 243  17%     for c in s:
 244  15%         assert tag or not quote
 245   0%
 246  15%         if c == '<' and not quote:
 247   3%             tag = True
 248  12%         elif c == '>' and not quote:
 249   3%             tag = False
 250   9%         elif (c == '"' or c == "'") and tag:
 251   0%             quote = not quote
 252   9%         elif not tag:
 253   4%             out = out + c
 254   0%
 255   3%     return out
debugger
 238 def remove_html_markup(s):  # type: ignore
 239     tag = False
 240     quote = False
 241     out = ""
 242  
 243     for c in s:
 244         assert tag or not quote
 245  
 246         if c == '<' and not quote:
 247             tag = True
 248         elif c == '>' and not quote:
 249             tag = False
 250         elif (c == '"' or c == "'") and tag:
 251             quote = not quote
 252         elif not tag:
 253             out = out + c
 254  
 255     return out

Integrating with Delta Debugging

Besides identifying causes for performance issues in the code, one may also search for causes in the input, using Delta Debugging. This can be useful if one does not immediately want to embark into investigating the code, but maybe first determine external influences that are related to performance issues.

Here is a variant of remove_html_markup() that introduces a (rather obvious) performance issue.

import time
def remove_html_markup_ampersand(s: str) -> str:
    tag = False
    quote = False
    out = ""

    for c in s:
        assert tag or not quote

        if c == '&':
            time.sleep(0.1)  # <-- the obvious performance issue

        if c == '<' and not quote:
            tag = True
        elif c == '>' and not quote:
            tag = False
        elif (c == '"' or c == "'") and tag:
            quote = not quote
        elif not tag:
            out = out + c

    return out

We can easily trigger this issue by measuring time taken:

with Timer.Timer() as t:
    remove_html_markup_ampersand('&&&')
t.elapsed_time()
0.31061120895901695

Let us set up a test that checks whether the performance issue is present.

def remove_html_test(s: str) -> None:
    with Timer.Timer() as t:
        remove_html_markup_ampersand(s)
    assert t.elapsed_time() < 0.1

We can now apply delta debugging to determine a minimum input that causes the failure:

s_fail = '<b>foo&amp;</b>'
with DeltaDebugger.DeltaDebugger() as dd:
    remove_html_test(s_fail)
dd.min_args()
{'s': '&'}

For performance issues, however, a minimal input is often not enough to highlight the failure cause. This is because short inputs tend to take less processing time than longer inputs, which increases the risks of a spurious diagnosis. A better alternative is to compute a maximum input where the issue does not occur:

s_pass = dd.max_args()
s_pass
{'s': '<b>fooamp;</b>'}

We see that the culprit character (the &) is removed. This tells us the failure-inducing difference – or, more precisely, the cause for the performance issue.

Lessons Learned

  • To measure performance,
    • instrument the code such that the time taken per function (or line) is collected; or
    • sample the execution that at regular intervals, the active call stack is collected.
  • To make code performant, focus on efficient algorithms, efficient data types, and sufficient abstraction such that you can replace them by alternatives.
  • Beyond efficient algorithms and data types, do not optimize before measuring.

Next Steps

This chapter concludes the part on abstracting failures. The next part will focus on

Background

Scalene is a high-performance, high-precision CPU, GPU, and memory profiler for Python. In contrast to the standard Python cProfile profiler, it uses sampling instead of instrumentation or relying on Python's tracing facilities; and it also supports line-by-line profiling. Scalene might be the tool of choice if you want to go beyond basic profiling.

The Wikipedia articles on profiling) and performance analysis tools provide several additional resources on profiling tools and how to apply them in practice.

Exercises

Exercise 1: Profiling Memory Usage

The Python tracemalloc module allows tracking memory usage during execution. Between tracemalloc.start() and tracemalloc.end(), use tracemalloc.get_traced_memory() to obtain how much memory is currently being consumed:

import tracemalloc
tracemalloc.start()
current_size, peak_size = tracemalloc.get_traced_memory()
current_size
20539
tracemalloc.stop()

Create a subclass of MetricCollector named MemoryCollector. Make it measure the memory consumption before and after each line executed (0 if negative), and visualize the impact of individual lines on memory. Create an appropriate test program that (temporarily) consumes larger amounts of memory.

Exercise 2: Statistical Performance Debugging

In a similar way as we integrated a binary "performance test" with delta debugging, we can also integrate such a test with other techniques. Combining a performance test with Statistical Debugging, for instance, will highlight those lines whose execution correlates with low performance. But then, the performance test need not be binary, as with functional pass/fail tests – you can also weight individual lines by how much they impact performance. Create a variant of StatisticalDebugger that reflects the impact of individual lines on an arbitrary (summarized) performance metric.

Creative Commons License The content of this project is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. The source code that is part of the content, as well as the source code used to format and display that content is licensed under the MIT License. Last change: 2023-11-16 15:49:39+01:00CiteImprint