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.
Prerequisites
- This chapter leverages visualization capabilities from the chapter on statistical debugging.
- We also show how to debug nonfunctional issues using delta debugging.
Measuring Performance¶
The solution to debugging performance issues fits in two simple rules:
- Measure performance
- 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
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
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:
with Timer.Timer() as t:
change_counter = debuggingbook_change_counter(ChangeCounter)
t.elapsed_time()
122.19405049999477
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
(firstpercall
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
(secondpercall
column)
Let us have a look at the profile we obtain:
cProfile.run('debuggingbook_change_counter(ChangeCounter)', sort='cumulative')
40923613 function calls (40726720 primitive calls) in 141.560 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 2588 0.015 0.000 253.988 0.098 threading.py:1117(join) 2602/2597 0.019 0.000 253.906 0.098 threading.py:1155(_wait_for_tstate_lock) 23564/18378 0.078 0.000 246.948 0.013 {method 'acquire' of '_thread.lock' objects} 1344 0.010 0.000 141.941 0.106 repository.py:213(traverse_commits) 2/1 0.000 0.000 141.559 141.559 {built-in method builtins.exec} 2/1 0.001 0.001 141.559 141.559 <string>:1(<module>) 2/1 0.000 0.000 141.558 141.558 ChangeCounter.ipynb:168(debuggingbook_change_counter) 1 0.000 0.000 141.558 141.558 ChangeCounter.ipynb:51(__init__) 1 0.000 0.000 141.558 141.558 ChangeCounter.ipynb:88(mine) 1 0.000 0.000 141.515 141.515 _base.py:646(__exit__) 1 0.000 0.000 141.515 141.515 thread.py:220(shutdown) 2588/1 0.033 0.000 141.515 141.515 threading.py:1018(_bootstrap) 2588/1 0.015 0.000 141.514 141.514 threading.py:1058(_bootstrap_inner) 2588/1 0.012 0.000 141.514 141.514 ipkernel.py:744(run_closure) 2588/1 10.482 0.004 141.514 141.514 threading.py:1001(run) 4/1 0.001 0.000 141.514 141.514 thread.py:70(_worker) 16/2 0.026 0.002 141.514 70.757 {method 'get' of '_queue.SimpleQueue' objects} 1343 0.171 0.000 141.099 0.105 ChangeCounter.ipynb:102(mine_commit) 1343 0.039 0.000 138.416 0.103 commit.py:753(modified_files) 1292 0.403 0.000 138.333 0.107 diff.py:184(diff) 1292 13.969 0.011 106.419 0.082 diff.py:583(_index_from_patch_format) 1292 0.054 0.000 90.116 0.070 cmd.py:97(handle_process_output) 2584/1292 44.067 0.017 66.896 0.052 cmd.py:144(pump_stream) 139 35.623 0.256 55.517 0.399 {built-in method time.sleep} 14793 0.091 0.000 20.915 0.001 diff.py:412(__init__) 13967 0.020 0.000 20.491 0.001 base.py:481(submodules) 13967 0.047 0.000 20.472 0.001 util.py:1270(list_items) 32492/32486 0.057 0.000 20.408 0.001 {method 'extend' of 'list' objects} 41901 0.194 0.000 20.351 0.000 base.py:1571(iter_items) 5280/5075 0.048 0.000 12.046 0.002 {method 'close' of '_io.BufferedReader' objects} 1347 0.081 0.000 8.449 0.006 cmd.py:1523(_call_process) 1347 0.145 0.000 8.335 0.006 cmd.py:1079(execute) 1293 0.048 0.000 8.168 0.006 cmd.py:986(<lambda>) 1347 0.139 0.000 7.781 0.006 subprocess.py:807(__init__) 1347 0.232 0.000 7.521 0.006 subprocess.py:1791(_execute_child) 41901 0.042 0.000 7.411 0.000 base.py:715(commit) 71178 0.093 0.000 6.998 0.000 util.py:248(__getattr__) 128771 0.396 0.000 6.813 0.000 cmd.py:1659(__get_object_header) 41901 0.028 0.000 6.616 0.000 symbolic.py:290(_get_commit) 41901 0.053 0.000 6.589 0.000 symbolic.py:280(_get_object) 97769/27934 0.064 0.000 5.625 0.000 tree.py:361(__getitem__) 229638 5.602 0.000 5.602 0.000 {method 'readline' of '_io.BufferedReader' objects} 97769/27934 0.255 0.000 5.590 0.000 tree.py:231(join) 55868 0.051 0.000 5.561 0.000 symbolic.py:156(dereference_recursive) 111737 0.121 0.000 5.507 0.000 symbolic.py:269(_get_ref_info) 111737 0.362 0.000 5.386 0.000 symbolic.py:221(_get_ref_info_helper) 72903 0.166 0.000 5.246 0.000 db.py:44(stream) 55868 0.065 0.000 4.946 0.000 tree.py:210(_set_cache_) 72903 0.195 0.000 4.935 0.000 cmd.py:1695(stream_object_data) 1347 4.542 0.003 4.542 0.003 {built-in method _posixsubprocess.fork_exec} 31 0.004 0.000 3.580 0.115 base_events.py:1915(_run_once) 13967 0.057 0.000 3.514 0.000 base.py:229(_config_parser) 55868 0.125 0.000 3.479 0.000 base.py:136(new_from_sha) 55868 0.130 0.000 3.000 0.000 db.py:39(info) 55868 0.069 0.000 2.761 0.000 cmd.py:1667(get_object_header) 13967 0.059 0.000 2.650 0.000 fun.py:230(rev_parse) 13967 0.050 0.000 2.580 0.000 fun.py:150(name_to_object) 1347 2.145 0.002 2.145 0.002 {built-in method posix.read} 128875 1.941 0.000 2.011 0.000 {built-in method _io.open} 15310 0.039 0.000 1.948 0.000 commit.py:241(_set_cache_) 111945 1.754 0.000 1.852 0.000 {method 'read' of '_io.TextIOWrapper' objects} 864 0.027 0.000 1.790 0.002 ChangeCounter.ipynb:121(update_stats) 1726 0.003 0.000 1.729 0.001 commit.py:214(content) 1726 0.004 0.000 1.726 0.001 commit.py:222(_get_undecoded_content) 112057/97876 0.114 0.000 1.695 0.000 config.py:111(assure_data_present) 72903 0.079 0.000 1.479 0.000 cmd.py:863(read) 13967 0.024 0.000 1.456 0.000 util.py:82(__init__) 14073 0.056 0.000 1.443 0.000 config.py:315(__init__) 57593 0.026 0.000 1.408 0.000 base.py:137(read) 145805 1.392 0.000 1.392 0.000 {method 'read' of '_io.BufferedReader' objects} 14073 0.077 0.000 1.382 0.000 configparser.py:582(__init__) 112057/97985 0.084 0.000 1.266 0.000 config.py:589(read) 1292 1.196 0.001 1.196 0.001 {method 'join' of 'bytes' objects} 55868 0.706 0.000 1.125 0.000 fun.py:77(tree_entries_from_data) 14073 0.245 0.000 1.049 0.000 configparser.py:1287(__init__) 14073 0.328 0.000 0.866 0.000 config.py:439(_read) 14071080 0.839 0.000 0.839 0.000 {method 'append' of 'list' objects} 1725 0.001 0.000 0.770 0.000 base.py:192(data_stream) 111737 0.401 0.000 0.766 0.000 symbolic.py:173(_check_ref_name_valid) 15310 0.137 0.000 0.636 0.000 commit.py:782(_deserialize) 14793 0.005 0.000 0.540 0.000 ChangeCounter.ipynb:112(include) 14793 0.016 0.000 0.535 0.000 ChangeCounter.ipynb:176(filter) 35801 0.057 0.000 0.533 0.000 commit.py:276(new_path) 14073 0.521 0.000 0.521 0.000 {built-in method builtins.dir} 128771 0.033 0.000 0.445 0.000 cmd.py:1646(_get_persistent_cmd) 16136 0.006 0.000 0.403 0.000 commit.py:633(committer_date) 16136 0.007 0.000 0.397 0.000 commit.py:254(committed_datetime) 1929795 0.394 0.000 0.394 0.000 {method 'match' of 're.Pattern' objects} 35425 0.054 0.000 0.376 0.000 pathlib.py:437(__str__) 863310 0.367 0.000 0.367 0.000 cmd.py:972(__getattribute__) 488845 0.173 0.000 0.338 0.000 compat.py:117(safe_decode) 158162 0.198 0.000 0.324 0.000 posixpath.py:71(join) 128771 0.317 0.000 0.317 0.000 {method 'flush' of '_io.BufferedWriter' objects} 2686 0.025 0.000 0.299 0.000 repository.py:245(_iter_commits) 1347 0.092 0.000 0.285 0.000 subprocess.py:1282(_close_pipe_fds) 35424 0.027 0.000 0.283 0.000 pathlib.py:551(drive) 55973 0.069 0.000 0.282 0.000 configparser.py:743(get) 113141 0.168 0.000 0.279 0.000 base.py:231(__init__) 35422 0.022 0.000 0.256 0.000 pathlib.py:407(_load_parts) 30620 0.088 0.000 0.254 0.000 util.py:326(parse_actor_and_date) 1347 0.040 0.000 0.248 0.000 os.py:748(copy) 14073 0.140 0.000 0.237 0.000 configparser.py:1210(__init__) 126022 0.232 0.000 0.232 0.000 {method '__exit__' of '_io._IOBase' objects} 57211 0.043 0.000 0.232 0.000 tree.py:192(__init__) 128771 0.156 0.000 0.231 0.000 cmd.py:1601(_parse_object_header) 35422 0.060 0.000 0.227 0.000 pathlib.py:387(_parse_path) 1063316 0.176 0.000 0.226 0.000 {built-in method builtins.getattr} 55868 0.117 0.000 0.216 0.000 util.py:111(get_object_type_by_name) 1159555 0.211 0.000 0.211 0.000 {method 'decode' of 'bytes' objects} 128771 0.113 0.000 0.208 0.000 cmd.py:1632(_prepare_ref) 789663 0.125 0.000 0.206 0.000 cmd.py:792(__getattr__) 185713 0.161 0.000 0.205 0.000 base.py:100(__init__) 2070017/2070013 0.193 0.000 0.198 0.000 {built-in method builtins.isinstance} 28272 0.133 0.000 0.197 0.000 util.py:91(mode_str_to_int) 113029 0.067 0.000 0.186 0.000 {built-in method builtins.any} 2588 0.010 0.000 0.171 0.000 ipkernel.py:768(init_closure) 2588 0.079 0.000 0.161 0.000 threading.py:884(__init__) 2234728 0.159 0.000 0.159 0.000 {built-in method builtins.ord} 16136 0.018 0.000 0.153 0.000 util.py:211(from_timestamp) 72572 0.053 0.000 0.151 0.000 commit.py:109(__init__) 2588 0.020 0.000 0.142 0.000 threading.py:975(start) 228990 0.073 0.000 0.136 0.000 os.py:841(fsencode) 97873 0.092 0.000 0.133 0.000 util.py:272(join_path) 128302 0.130 0.000 0.130 0.000 {built-in method sys.intern} 95742 0.051 0.000 0.125 0.000 os.py:709(__getitem__) 4041 0.069 0.000 0.121 0.000 contextlib.py:530(callback) 335210 0.071 0.000 0.119 0.000 symbolic.py:215(<genexpr>) 27934 0.018 0.000 0.118 0.000 base.py:437(index) 374492 0.115 0.000 0.115 0.000 {method 'split' of 'str' objects} 549364 0.110 0.000 0.110 0.000 {method 'endswith' of 'str' objects} 55973 0.056 0.000 0.107 0.000 configparser.py:1122(_unify_values) 27934 0.017 0.000 0.100 0.000 base.py:140(__init__) 111945 0.069 0.000 0.098 0.000 codecs.py:319(decode) 55973 0.065 0.000 0.097 0.000 __init__.py:1009(__getitem__) 1347 0.044 0.000 0.094 0.000 util.py:529(remove_password_if_present) 14076 0.010 0.000 0.093 0.000 config.py:536(_has_includes) 878243 0.091 0.000 0.091 0.000 {built-in method builtins.len} 2588 0.089 0.000 0.089 0.000 {built-in method _thread.start_new_thread} 1347 0.018 0.000 0.089 0.000 subprocess.py:1688(_get_handles) 99058 0.082 0.000 0.089 0.000 config.py:205(__setitem__) 27934 0.013 0.000 0.082 0.000 base.py:172(_index_path) 14072 0.021 0.000 0.082 0.000 config.py:539(_included_paths) 96984 0.016 0.000 0.081 0.000 _collections_abc.py:868(__iter__) 32328 0.013 0.000 0.080 0.000 subprocess.py:1880(<genexpr>) 139926 0.062 0.000 0.079 0.000 config.py:218(__getitem__) 323273 0.079 0.000 0.079 0.000 {method 'startswith' of 'str' objects} 29586 0.011 0.000 0.077 0.000 diff.py:570(_pick_best_path) 89658 0.077 0.000 0.077 0.000 {method 'search' of 're.Pattern' objects} 453635 0.076 0.000 0.076 0.000 {method 'encode' of 'str' objects} 27934 0.019 0.000 0.074 0.000 base.py:122(__init__) 30620 0.033 0.000 0.072 0.000 util.py:808(_from_string) 105 0.006 0.000 0.072 0.001 base.py:172(__init__) 104 0.000 0.000 0.072 0.001 util.py:171(wrapper) 104 0.001 0.000 0.072 0.001 base.py:1404(module) 2588 0.029 0.000 0.070 0.000 threading.py:637(wait) 16136 0.062 0.000 0.070 0.000 {built-in method fromtimestamp} 28038 0.023 0.000 0.069 0.000 util.py:309(join_path_native) 111945 0.054 0.000 0.067 0.000 codecs.py:309(__init__) 29586 0.034 0.000 0.067 0.000 diff.py:105(decode_path) 1347 0.030 0.000 0.066 0.000 os.py:654(get_exec_path) 96984 0.037 0.000 0.066 0.000 os.py:732(__iter__) 35527 0.021 0.000 0.062 0.000 pathlib.py:1157(__init__) 41902 0.026 0.000 0.061 0.000 base.py:450(head) 191274 0.029 0.000 0.059 0.000 os.py:795(decode) 1293 0.011 0.000 0.054 0.000 util.py:500(finalize_process) 159442 0.054 0.000 0.054 0.000 {method 'split' of 'bytes' objects} 169638 0.053 0.000 0.053 0.000 typing.py:392(inner) 1344 0.008 0.000 0.053 0.000 _base.py:612(result_iterator) 55874 0.034 0.000 0.052 0.000 <frozen importlib._bootstrap>:1390(_handle_fromlist) 111737 0.041 0.000 0.052 0.000 symbolic.py:52(_git_dir) 161591 0.030 0.000 0.050 0.000 posixpath.py:41(_get_sep) 72903 0.030 0.000 0.049 0.000 base.py:128(__new__) 300400 0.049 0.000 0.049 0.000 {method 'strip' of 'str' objects} 2640 0.005 0.000 0.048 0.000 subprocess.py:1259(wait) 55869 0.027 0.000 0.048 0.000 <frozen importlib._bootstrap>:645(parent) 1403 0.009 0.000 0.048 0.000 cmd.py:789(__del__) 244649 0.047 0.000 0.047 0.000 {built-in method binascii.a2b_hex} 2585 0.025 0.000 0.047 0.000 cmd.py:796(wait) 52 0.001 0.000 0.047 0.001 base.py:1427(module_exists) 16136 0.041 0.000 0.047 0.000 {method 'astimezone' of 'datetime.datetime' objects} 27934 0.033 0.000 0.045 0.000 symbolic.py:596(to_full_path) 179588 0.044 0.000 0.044 0.000 {built-in method __new__ of type object at 0x10195c990} 95742 0.024 0.000 0.044 0.000 os.py:791(encode) 1343 0.027 0.000 0.044 0.000 _base.py:314(_result_or_cancel) 1293 0.003 0.000 0.044 0.000 subprocess.py:1135(_get_devnull) 155815 0.044 0.000 0.044 0.000 {method 'group' of 're.Match' objects} 2640 0.005 0.000 0.043 0.000 subprocess.py:2021(_wait) 3915 0.007 0.000 0.042 0.000 threading.py:323(wait) 35527 0.025 0.000 0.041 0.000 pathlib.py:358(__init__) 1293 0.041 0.000 0.041 0.000 {built-in method posix.open} 497792 0.040 0.000 0.040 0.000 {built-in method posix.fspath} 1347 0.040 0.000 0.040 0.000 contextlib.py:481(__init__) 128903 0.040 0.000 0.040 0.000 {method 'write' of '_io.BufferedWriter' objects} 1344 0.000 0.000 0.039 0.000 git.py:110(get_list_commits) 55868 0.023 0.000 0.038 0.000 base.py:35(__new__) 27934 0.023 0.000 0.038 0.000 configparser.py:855(has_option) 147781 0.038 0.000 0.038 0.000 {method 'startswith' of 'bytes' objects} 1403 0.004 0.000 0.037 0.000 cmd.py:754(_terminate) 1348 0.003 0.000 0.037 0.000 subprocess.py:2008(_try_wait) 28039 0.028 0.000 0.036 0.000 configparser.py:630(sections) 4041 0.035 0.000 0.035 0.000 contextlib.py:475(_create_cb_wrapper) 41903 0.031 0.000 0.035 0.000 head.py:50(__init__) 1458 0.034 0.000 0.034 0.000 {built-in method posix.waitpid} 35422 0.016 0.000 0.033 0.000 pathlib.py:429(_format_parsed_parts) 2588 0.005 0.000 0.033 0.000 threading.py:588(__init__) 169275 0.033 0.000 0.033 0.000 {method 'rstrip' of 'str' objects} 85328 0.019 0.000 0.033 0.000 diff.py:535(b_path) 30620 0.025 0.000 0.033 0.000 util.py:146(utctz_to_altz) 107 0.000 0.000 0.032 0.000 cmd.py:1710(clear_cache) 1344 0.002 0.000 0.031 0.000 commit.py:512(_iter_from_process_or_stream) 1347 0.020 0.000 0.030 0.000 contextlib.py:567(__exit__) 14793 0.008 0.000 0.030 0.000 commit.py:595(committer) 134194 0.029 0.000 0.029 0.000 {built-in method binascii.b2a_hex} 100506 0.028 0.000 0.028 0.000 typing.py:1766(_no_init_or_replace_init) 111945 0.028 0.000 0.028 0.000 {built-in method _codecs.utf_8_decode} 6735 0.028 0.000 0.028 0.000 {built-in method posix.close} 2588 0.003 0.000 0.028 0.000 threading.py:616(set) 1323 0.020 0.000 0.028 0.000 parse.py:452(urlsplit) 70419 0.027 0.000 0.027 0.000 {built-in method builtins.setattr} 57122 0.027 0.000 0.027 0.000 config.py:208(add) 1536 0.016 0.000 0.027 0.000 ipkernel.py:775(_clean_thread_parent_frames) 76033 0.027 0.000 0.027 0.000 {method 'groups' of 're.Match' objects} 1 0.001 0.001 0.026 0.026 _base.py:583(map) 140311 0.025 0.000 0.025 0.000 {built-in method builtins.hasattr} 12978/1347 0.013 0.000 0.025 0.000 cmd.py:1477(_unpack_args) 2588 0.025 0.000 0.025 0.000 threading.py:1356(_make_invoke_excepthook) 84629 0.025 0.000 0.025 0.000 {method 'rpartition' of 'str' objects} 105 0.000 0.000 0.024 0.000 base.py:327(__del__) 105 0.001 0.000 0.024 0.000 base.py:333(close) 1347 0.023 0.000 0.023 0.000 warnings.py:484(__enter__) 3932 0.019 0.000 0.023 0.000 threading.py:277(__init__) 72903 0.022 0.000 0.022 0.000 base.py:132(__init__) 35422 0.014 0.000 0.020 0.000 posixpath.py:138(splitroot) 27934 0.014 0.000 0.019 0.000 util.py:42(sm_name) 3932 0.007 0.000 0.019 0.000 threading.py:424(notify_all) 1343 0.014 0.000 0.019 0.000 commit.py:796(_parse_diff) 16136 0.019 0.000 0.019 0.000 util.py:191(__init__) 13967 0.014 0.000 0.018 0.000 util.py:1169(__new__) 55868 0.017 0.000 0.017 0.000 base.py:38(__init__) 140058 0.017 0.000 0.017 0.000 {function _OMD.__getitem__ at 0x127f64ae0} 4041 0.014 0.000 0.016 0.000 contextlib.py:548(_push_exit_callback) 2696 0.002 0.000 0.016 0.000 {built-in method builtins.next} 418/210 0.001 0.000 0.016 0.000 fun.py:99(find_submodule_git_dir) 35527 0.010 0.000 0.016 0.000 pathlib.py:1164(__new__) 4095 0.016 0.000 0.016 0.000 {built-in method posix.pipe} 1343 0.002 0.000 0.015 0.000 thread.py:165(submit) 11908 0.009 0.000 0.015 0.000 threading.py:299(__enter__) 85660 0.015 0.000 0.015 0.000 {method 'lower' of 'str' objects} 16136 0.013 0.000 0.014 0.000 mailmap.py:16(get_developer) 28272 0.014 0.000 0.014 0.000 {method 'sub' of 're.Pattern' objects} 1343 0.007 0.000 0.014 0.000 _base.py:428(result) 2 0.000 0.000 0.014 0.007 repository.py:179(_prep_repo) 55973 0.013 0.000 0.013 0.000 __init__.py:999(__init__) 2588 0.013 0.000 0.013 0.000 threading.py:1042(_set_native_id) 201723 0.013 0.000 0.013 0.000 typing.py:2183(cast) 1292 0.013 0.000 0.013 0.000 {method 'finditer' of 're.Pattern' objects} 30620 0.010 0.000 0.013 0.000 util.py:789(__init__) 14380 0.006 0.000 0.013 0.000 parse.py:160(password) 27934 0.008 0.000 0.013 0.000 base.py:168(__ne__) 141030 0.012 0.000 0.012 0.000 config.py:435(optionxform) 1348 0.001 0.000 0.012 0.000 contextlib.py:141(__exit__) 28760 0.009 0.000 0.012 0.000 parse.py:193(_userinfo) 24230 0.008 0.000 0.012 0.000 conf.py:52(get) 7852 0.012 0.000 0.012 0.000 {built-in method _thread.allocate_lock} 111945 0.012 0.000 0.012 0.000 codecs.py:260(__init__) 77255 0.012 0.000 0.012 0.000 {method 'readline' of '_io.BytesIO' objects} 72903 0.012 0.000 0.012 0.000 cmd.py:852(__init__) 3948 0.004 0.000 0.012 0.000 threading.py:394(notify) 72903 0.011 0.000 0.011 0.000 cmd.py:939(__del__) 105 0.000 0.000 0.011 0.000 base.py:660(config_reader) 105 0.000 0.000 0.011 0.000 base.py:683(_config_reader) 55973 0.011 0.000 0.011 0.000 base.py:381(common_dir) 35313 0.008 0.000 0.011 0.000 posixpath.py:131(splitdrive) 33/31 0.001 0.000 0.010 0.000 events.py:86(_run) 2 0.000 0.000 0.010 0.005 git.py:77(clear) 864 0.007 0.000 0.009 0.000 ChangeCounter.ipynb:145(update_changes) 1348 0.005 0.000 0.009 0.000 contextlib.py:299(helper) 2588 0.005 0.000 0.009 0.000 _weakrefset.py:85(add) 523 0.001 0.000 0.009 0.000 fun.py:57(is_git_dir) 2584 0.009 0.000 0.009 0.000 threading.py:839(_newname) 33/31 0.001 0.000 0.009 0.000 {method 'run' of '_contextvars.Context' objects} 2588 0.003 0.000 0.008 0.000 threading.py:1045(_set_tstate_lock) 2588 0.007 0.000 0.008 0.000 threading.py:1108(_delete) 1347 0.003 0.000 0.008 0.000 warnings.py:168(simplefilter) 14087 0.004 0.000 0.008 0.000 config.py:398(__del__) 14793 0.005 0.000 0.008 0.000 commit.py:660(msg) 55868 0.008 0.000 0.008 0.000 base.py:52(type) 11908 0.007 0.000 0.008 0.000 threading.py:302(__exit__) 1343 0.001 0.000 0.008 0.000 thread.py:184(_adjust_thread_count) 1347 0.008 0.000 0.008 0.000 {built-in method posix.access} 14380 0.003 0.000 0.008 0.000 parse.py:156(username) 1 0.000 0.000 0.008 0.008 base.py:758(iter_commits) 1 0.000 0.000 0.008 0.008 commit.py:299(iter_items) 61240 0.007 0.000 0.007 0.000 {built-in method builtins.abs} 13782 0.005 0.000 0.007 0.000 diff.py:531(a_path) 1343 0.001 0.000 0.007 0.000 threading.py:468(acquire) 35423 0.007 0.000 0.007 0.000 {method 'join' of 'str' objects} 864 0.007 0.000 0.007 0.000 ChangeCounter.ipynb:137(update_size) 2902 0.004 0.000 0.007 0.000 posixpath.py:179(dirname) 64544 0.007 0.000 0.007 0.000 util.py:204(dst) 55868 0.007 0.000 0.007 0.000 base.py:60(size) 1348 0.002 0.000 0.007 0.000 contextlib.py:132(__enter__) 1472 0.006 0.000 0.006 0.000 {built-in method posix.stat} 70365 0.006 0.000 0.006 0.000 {built-in method builtins.callable} 1343 0.004 0.000 0.006 0.000 commit.py:559(hash) 13967 0.004 0.000 0.006 0.000 base.py:162(__eq__) 49751 0.006 0.000 0.006 0.000 util.py:198(utcoffset) 5176 0.005 0.000 0.006 0.000 threading.py:1485(current_thread) 9200 0.006 0.000 0.006 0.000 {method 'release' of '_thread.lock' objects} 28039 0.006 0.000 0.006 0.000 {method 'keys' of 'collections.OrderedDict' objects} 55868 0.006 0.000 0.006 0.000 base.py:42(binsha) 14073 0.004 0.000 0.006 0.000 configparser.py:1329(__iter__) 768 0.005 0.000 0.006 0.000 threading.py:1535(enumerate) 1048 0.001 0.000 0.005 0.000 genericpath.py:39(isdir) 30981 0.005 0.000 0.005 0.000 {method 'endswith' of 'bytes' objects} 28038 0.005 0.000 0.005 0.000 util.py:303(to_native_path_linux) 1452 0.001 0.000 0.005 0.000 abc.py:117(__instancecheck__) 1347 0.002 0.000 0.005 0.000 warnings.py:184(_add_filter) 13642 0.005 0.000 0.005 0.000 threading.py:1198(ident) 4041 0.002 0.000 0.005 0.000 contextlib.py:477(_exit_wrapper) 1343 0.001 0.000 0.005 0.000 thread.py:54(run) 5423 0.002 0.000 0.005 0.000 base.py:186(hexsha) 55973 0.005 0.000 0.005 0.000 configparser.py:335(before_get) 25891 0.005 0.000 0.005 0.000 {method 'get' of 'dict' objects} 105 0.000 0.000 0.005 0.000 pathlib.py:1022(read_text) 1348 0.002 0.000 0.005 0.000 contextlib.py:104(__init__) 15416 0.005 0.000 0.005 0.000 {method 'pop' of 'list' objects} 105 0.000 0.000 0.005 0.000 pathlib.py:1005(open) 41903 0.004 0.000 0.004 0.000 symbolic.py:77(__init__) 28142 0.004 0.000 0.004 0.000 base.py:372(working_tree_dir) 3943 0.004 0.000 0.004 0.000 {method 'add' of 'set' objects} 1452 0.004 0.000 0.004 0.000 {built-in method _abc._abc_instancecheck} 1347 0.004 0.000 0.004 0.000 {built-in method sys.exc_info} 1 0.000 0.000 0.004 0.004 git.py:39(__init__) 1343 0.000 0.000 0.004 0.000 _base.py:328(__init__) 2588 0.002 0.000 0.004 0.000 threading.py:1081(_stop) 6519 0.002 0.000 0.004 0.000 threading.py:314(_is_owned) 16711 0.004 0.000 0.004 0.000 {method 'strip' of 'bytes' objects} 1 0.000 0.000 0.004 0.004 git.py:86(_open_repository) 14088 0.003 0.000 0.004 0.000 config.py:410(release) 13967 0.004 0.000 0.004 0.000 fun.py:219(to_commit) 12257 0.004 0.000 0.004 0.000 cmd.py:338(__getattribute) 1344 0.003 0.000 0.004 0.000 __init__.py:1529(info) 14 0.001 0.000 0.004 0.000 iostream.py:118(_run_event_pipe_gc) 5373 0.004 0.000 0.004 0.000 {method '__enter__' of '_thread.RLock' objects} 14 0.001 0.000 0.004 0.000 futures.py:313(_set_result_unless_cancelled) 1323 0.004 0.000 0.004 0.000 parse.py:119(_coerce_args) 1347 0.001 0.000 0.004 0.000 __init__.py:1517(debug) 15310 0.003 0.000 0.003 0.000 {method 'read' of '_io.BytesIO' objects} 1343 0.001 0.000 0.003 0.000 commit.py:568(author) 7764 0.003 0.000 0.003 0.000 threading.py:1236(daemon) 1343 0.001 0.000 0.003 0.000 conf.py:272(is_commit_filtered) 109 0.000 0.000 0.003 0.000 pathlib.py:447(__fspath__) 2691 0.003 0.000 0.003 0.000 __init__.py:1790(isEnabledFor) 2588 0.002 0.000 0.003 0.000 _weakrefset.py:39(_remove) 14793 0.003 0.000 0.003 0.000 {method 'end' of 're.Match' objects} 35423 0.003 0.000 0.003 0.000 pathlib.py:569(_tail) 13905 0.003 0.000 0.003 0.000 {method '__exit__' of '_thread.RLock' objects} 2588 0.003 0.000 0.003 0.000 {built-in method _thread._set_sentinel} 35424 0.003 0.000 0.003 0.000 pathlib.py:560(root) 1344 0.001 0.000 0.003 0.000 _base.py:537(set_result) 7991 0.003 0.000 0.003 0.000 {method 'append' of 'collections.deque' objects} 1394 0.001 0.000 0.003 0.000 commit.py:669(parents) 16 0.002 0.000 0.003 0.000 {method 'set_result' of '_asyncio.Future' objects} 12940 0.003 0.000 0.003 0.000 {built-in method _thread.get_ident} 14073 0.002 0.000 0.003 0.000 config.py:378(_acquire_lock) 14793 0.002 0.000 0.003 0.000 commit.py:155(__init__) 2584 0.001 0.000 0.003 0.000 base.py:178(__str__) 2584 0.002 0.000 0.003 0.000 threading.py:1251(daemon) 9428 0.002 0.000 0.002 0.000 {method 'replace' of 'str' objects} 1343 0.001 0.000 0.002 0.000 _base.py:364(cancel) 1347 0.002 0.000 0.002 0.000 {method 'remove' of 'list' objects} 13501 0.002 0.000 0.002 0.000 {method 'start' of 're.Match' objects} 28 0.001 0.000 0.002 0.000 tasks.py:653(sleep) 2585 0.002 0.000 0.002 0.000 encoding.py:1(force_bytes) 55 0.001 0.000 0.002 0.000 subprocess.py:2208(terminate) 315 0.001 0.000 0.002 0.000 util.py:517(expand_path) 2696 0.001 0.000 0.002 0.000 subprocess.py:1233(poll) 3915 0.001 0.000 0.002 0.000 threading.py:311(_acquire_restore) 13967 0.002 0.000 0.002 0.000 util.py:1172(__init__) 2588 0.001 0.000 0.002 0.000 threading.py:1038(_set_ident) 6535 0.002 0.000 0.002 0.000 {method '__enter__' of '_thread.lock' objects} 2585 0.001 0.000 0.002 0.000 cmd.py:977(__getattr__) 14073 0.002 0.000 0.002 0.000 {built-in method builtins.iter} 1347 0.002 0.000 0.002 0.000 {built-in method builtins.sorted} 105 0.000 0.000 0.002 0.000 __init__.py:174(search) 105 0.000 0.000 0.002 0.000 configparser.py:804(getboolean) 3915 0.001 0.000 0.002 0.000 threading.py:308(_release_save) 1347 0.001 0.000 0.002 0.000 _collections_abc.py:819(keys) 1403 0.000 0.000 0.002 0.000 cmd.py:294(dashify) 105 0.000 0.000 0.002 0.000 configparser.py:783(_get_conv) 16136 0.002 0.000 0.002 0.000 developer.py:27(__init__) 14073 0.002 0.000 0.002 0.000 configparser.py:1170(converters) 105 0.001 0.000 0.001 0.000 __init__.py:280(_compile) 1348 0.001 0.000 0.001 0.000 subprocess.py:1961(_handle_exitstatus) 10596 0.001 0.000 0.001 0.000 {method '__exit__' of '_thread.lock' objects} 14071 0.001 0.000 0.001 0.000 base.py:390(bare) 105 0.000 0.000 0.001 0.000 configparser.py:780(_get) 1343 0.001 0.000 0.001 0.000 _base.py:497(set_running_or_notify_cancel) 2598 0.001 0.000 0.001 0.000 threading.py:1222(is_alive) 4041 0.001 0.000 0.001 0.000 {method 'pop' of 'collections.deque' objects} 1347 0.001 0.000 0.001 0.000 warnings.py:505(__exit__) 3915 0.001 0.000 0.001 0.000 {method 'remove' of 'collections.deque' objects} 105 0.000 0.000 0.001 0.000 db.py:34(__init__) 105 0.000 0.000 0.001 0.000 genericpath.py:16(exists) 5223 0.001 0.000 0.001 0.000 {method 'insert' of 'list' objects} 5403 0.001 0.000 0.001 0.000 {method 'items' of 'dict' objects} 3 0.000 0.000 0.001 0.000 config.py:710(write) 14091 0.001 0.000 0.001 0.000 config.py:764(read_only) 1348 0.001 0.000 0.001 0.000 subprocess.py:1120(__del__) 1347 0.001 0.000 0.001 0.000 cmd.py:1466(transform_kwargs) 1343 0.001 0.000 0.001 0.000 threading.py:124(RLock) 1323 0.001 0.000 0.001 0.000 <string>:1(<lambda>) 5168 0.001 0.000 0.001 0.000 diff.py:235(<genexpr>) 2588 0.001 0.000 0.001 0.000 {method 'discard' of 'set' objects} 1347 0.001 0.000 0.001 0.000 {method 'rfind' of 'bytes' objects} 1347 0.001 0.000 0.001 0.000 cmd.py:749(__init__) 2/1 0.000 0.000 0.001 0.001 config.py:127(flush_changes) 1347 0.001 0.000 0.001 0.000 contextlib.py:564(__enter__) 14 0.000 0.000 0.001 0.000 base_events.py:742(call_later) 313 0.000 0.000 0.001 0.000 cmd.py:662(is_cygwin) 317 0.000 0.000 0.001 0.000 genericpath.py:27(isfile) 16 0.000 0.000 0.001 0.000 base_events.py:784(call_soon) 105 0.000 0.000 0.001 0.000 pathlib.py:719(__truediv__) 4044 0.001 0.000 0.001 0.000 subprocess.py:1973(_internal_poll) 1 0.000 0.000 0.001 0.001 base.py:698(config_writer) 317 0.000 0.000 0.001 0.000 posixpath.py:408(abspath) 55 0.000 0.000 0.001 0.000 subprocess.py:2176(send_signal) 1323 0.001 0.000 0.001 0.000 {method 'lstrip' of 'str' objects} 14 0.000 0.000 0.001 0.000 base_events.py:766(call_at) 2 0.000 0.000 0.001 0.000 zmqstream.py:583(_handle_events) 14 0.000 0.000 0.001 0.000 iostream.py:127(_event_pipe_gc) 1555 0.001 0.000 0.001 0.000 {method 'rfind' of 'str' objects} 4 0.000 0.000 0.001 0.000 util.py:1050(_obtain_lock) 4 0.000 0.000 0.001 0.000 util.py:1026(_obtain_lock_or_raise) 105 0.000 0.000 0.001 0.000 loose.py:77(__init__) 105 0.000 0.000 0.001 0.000 pathlib.py:711(joinpath) 1 0.000 0.000 0.001 0.001 config.py:866(set_value) 7774 0.001 0.000 0.001 0.000 threading.py:601(is_set) 105 0.000 0.000 0.001 0.000 cmd.py:947(__init__) 1 0.000 0.000 0.001 0.001 asyncio.py:200(_handle_events) 14 0.001 0.000 0.001 0.000 events.py:155(cancel) 1323 0.001 0.000 0.001 0.000 {method 'find' of 'str' objects} 2 0.000 0.000 0.001 0.000 zmqstream.py:624(_handle_recv) 1347 0.001 0.000 0.001 0.000 subprocess.py:268(_cleanup) 55 0.001 0.000 0.001 0.000 {built-in method posix.kill} 55 0.001 0.000 0.001 0.000 {method 'close' of '_io.BufferedWriter' objects} 31 0.000 0.000 0.001 0.000 events.py:36(__init__) 313 0.000 0.000 0.001 0.000 util.py:486(is_cygwin_git) 4041 0.001 0.000 0.001 0.000 {built-in method _warnings._filters_mutated} 527 0.000 0.000 0.001 0.000 posixpath.py:60(isabs) 1343 0.001 0.000 0.001 0.000 _base.py:398(__get_result) 1343 0.000 0.000 0.001 0.000 git.py:140(get_commit_from_gitpython) 1051 0.001 0.000 0.001 0.000 {built-in method posix._path_normpath} 14 0.000 0.000 0.001 0.000 events.py:111(__init__) 3072 0.001 0.000 0.001 0.000 {method 'keys' of 'dict' objects} 1452 0.001 0.000 0.001 0.000 {method 'pop' of 'dict' objects} 105 0.000 0.000 0.001 0.000 base.py:113(__init__) 105 0.000 0.000 0.000 0.000 _collections_abc.py:811(__contains__) 1401 0.000 0.000 0.000 0.000 {method 'update' of 'dict' objects} 17 0.000 0.000 0.000 0.000 base_events.py:813(_call_soon) 140 0.000 0.000 0.000 0.000 {built-in method posix.getppid} 107 0.000 0.000 0.000 0.000 pathlib.py:380(with_segments) 106 0.000 0.000 0.000 0.000 base.py:633(_get_config_path) 1641 0.000 0.000 0.000 0.000 {method 'values' of 'dict' objects} 2588 0.000 0.000 0.000 0.000 {built-in method _thread.get_native_id} 1347 0.000 0.000 0.000 0.000 warnings.py:458(__init__) 16 0.000 0.000 0.000 0.000 {method 'cancelled' of '_asyncio.Future' objects} 2 0.000 0.000 0.000 0.000 pathlib.py:1228(resolve) 105 0.000 0.000 0.000 0.000 mman.py:408(collect) 2606 0.000 0.000 0.000 0.000 {method 'locked' of '_thread.lock' objects} 2 0.000 0.000 0.000 0.000 zmqstream.py:556(_run_callback) 2584 0.000 0.000 0.000 0.000 {built-in method _thread.daemon_threads_allowed} 104 0.000 0.000 0.000 0.000 base.py:288(abspath) 3 0.000 0.000 0.000 0.000 config.py:664(_write) 16 0.000 0.000 0.000 0.000 {built-in method _contextvars.copy_context} 1348 0.000 0.000 0.000 0.000 {built-in method posix.WIFSTOPPED} 315 0.000 0.000 0.000 0.000 posixpath.py:256(expanduser) 45 0.000 0.000 0.000 0.000 config.py:668(write_section) 2717 0.000 0.000 0.000 0.000 {built-in method time.monotonic} 313 0.000 0.000 0.000 0.000 util.py:455(_is_cygwin_git) 1348 0.000 0.000 0.000 0.000 {built-in method posix.waitstatus_to_exitcode} 2694 0.000 0.000 0.000 0.000 subprocess.py:1311(_on_error_fd_closer) 1347 0.000 0.000 0.000 0.000 {built-in method sys.audit} 61 0.000 0.000 0.000 0.000 base_events.py:733(time) 1348 0.000 0.000 0.000 0.000 {method 'put' of '_queue.SimpleQueue' objects} 2 0.000 0.000 0.000 0.000 iostream.py:157(_handle_event) 1323 0.000 0.000 0.000 0.000 parse.py:421(_checknetloc) 1347 0.000 0.000 0.000 0.000 {method 'get_nowait' of '_queue.SimpleQueue' objects} 2 0.000 0.000 0.000 0.000 iostream.py:276(<lambda>) 58 0.000 0.000 0.000 0.000 cmd.py:1450(transform_kwarg) 1347 0.000 0.000 0.000 0.000 _collections_abc.py:845(__init__) 315 0.000 0.000 0.000 0.000 posixpath.py:320(expandvars) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1344 0.000 0.000 0.000 0.000 _base.py:337(_invoke_callbacks) 2 0.000 0.000 0.000 0.000 ioloop.py:742(_run_callback) 105 0.000 0.000 0.000 0.000 configparser.py:1142(_convert_to_boolean) 2 0.000 0.000 0.000 0.000 iostream.py:278(_really_send) 2 0.000 0.000 0.000 0.000 socket.py:703(send_multipart) 1292 0.000 0.000 0.000 0.000 diff.py:172(_process_diff_args) 2 0.000 0.000 0.000 0.000 posixpath.py:423(realpath) 5 0.000 0.000 0.000 0.000 attrsettr.py:43(__getattr__) 105 0.000 0.000 0.000 0.000 mman.py:303(_collect_lru_region) 1343 0.000 0.000 0.000 0.000 thread.py:48(__init__) 2 0.000 0.000 0.000 0.000 posixpath.py:432(_joinrealpath) 1 0.000 0.000 0.000 0.000 git.py:92(_discover_main_branch) 943 0.000 0.000 0.000 0.000 {built-in method _stat.S_ISDIR} 1323 0.000 0.000 0.000 0.000 parse.py:108(_noop) 14 0.000 0.000 0.000 0.000 events.py:72(cancel) 3 0.000 0.000 0.000 0.000 zmqstream.py:663(_rebuild_io_state) 1343 0.000 0.000 0.000 0.000 commit.py:536(__init__) 1 0.000 0.000 0.000 0.000 base.py:1041(active_branch) 104 0.000 0.000 0.000 0.000 base.py:351(__ne__) 8 0.000 0.000 0.000 0.000 {built-in method posix.lstat} 14 0.000 0.000 0.000 0.000 base_events.py:446(create_future) 1 0.000 0.000 0.000 0.000 symbolic.py:402(_get_reference) 5 0.000 0.000 0.000 0.000 attrsettr.py:66(_get_attr_opt) 1344 0.000 0.000 0.000 0.000 {method '_is_owned' of '_thread.RLock' objects} 46 0.000 0.000 0.000 0.000 {built-in method builtins.max} 864 0.000 0.000 0.000 0.000 ChangeCounter.ipynb:155(update_elems) 3 0.000 0.000 0.000 0.000 zmqstream.py:686(_update_handler) 14 0.000 0.000 0.000 0.000 socket.py:626(send) 1 0.000 0.000 0.000 0.000 kernelbase.py:324(_flush) 45 0.000 0.000 0.000 0.000 config.py:242(items_all) 2 0.000 0.000 0.000 0.000 util.py:1057(_release_lock) 88 0.000 0.000 0.000 0.000 config.py:861(_value_to_string) 32 0.000 0.000 0.000 0.000 selector_events.py:750(_process_events) 1 0.000 0.000 0.000 0.000 zmqstream.py:694(<lambda>) 1 0.000 0.000 0.000 0.000 util.py:245(rmfile) 14 0.000 0.000 0.000 0.000 {built-in method _heapq.heappop} 16 0.000 0.000 0.000 0.000 enum.py:1545(__or__) 1 0.000 0.000 0.000 0.000 zmqstream.py:427(flush) 1 0.000 0.000 0.000 0.000 {built-in method posix.remove} 104 0.000 0.000 0.000 0.000 base.py:346(__eq__) 132 0.000 0.000 0.000 0.000 config.py:235(getall) 4 0.000 0.000 0.000 0.000 weakref.py:369(remove) 14 0.000 0.000 0.000 0.000 {built-in method _heapq.heappush} 1 0.000 0.000 0.000 0.000 kernelbase.py:302(poll_control_queue) 16 0.000 0.000 0.000 0.000 threading.py:515(release) 1 0.000 0.000 0.000 0.000 conf.py:85(sanity_check_filters) 72 0.000 0.000 0.000 0.000 enum.py:1538(_get_value) 2 0.000 0.000 0.000 0.000 pathlib.py:835(stat) 8 0.000 0.000 0.000 0.000 enum.py:1556(__and__) 1 0.000 0.000 0.000 0.000 symbolic.py:879(from_path) 1 0.000 0.000 0.000 0.000 selector_events.py:129(_read_from_self) 3 0.000 0.000 0.000 0.000 config.py:238(items) 58 0.000 0.000 0.000 0.000 {method 'find' of 'bytes' objects} 211 0.000 0.000 0.000 0.000 {built-in method _stat.S_ISREG} 8 0.000 0.000 0.000 0.000 threading.py:857(_maintain_shutdown_locks) 1 0.000 0.000 0.000 0.000 thread.py:127(__init__) 210 0.000 0.000 0.000 0.000 {built-in method _io.text_encoding} 1 0.000 0.000 0.000 0.000 conf.py:302(_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:310(_replace_timezone) 2 0.000 0.000 0.000 0.000 pathlib.py:1398(expanduser) 88 0.000 0.000 0.000 0.000 encoding.py:11(force_text) 31 0.000 0.000 0.000 0.000 enum.py:720(__call__) 2 0.000 0.000 0.000 0.000 socket.py:774(recv_multipart) 1 0.000 0.000 0.000 0.000 queues.py:186(put) 2 0.000 0.000 0.000 0.000 {method 'recv' of '_socket.socket' objects} 1 0.000 0.000 0.000 0.000 zmqstream.py:468(update_flag) 58 0.000 0.000 0.000 0.000 {method 'rstrip' of 'bytes' objects} 107 0.000 0.000 0.000 0.000 {built-in method builtins.issubclass} 1 0.000 0.000 0.000 0.000 queues.py:209(put_nowait) 1 0.000 0.000 0.000 0.000 futures.py:396(_call_set_state) 1 0.000 0.000 0.000 0.000 conf.py:26(__init__) 105 0.000 0.000 0.000 0.000 base.py:70(__init__) 4 0.000 0.000 0.000 0.000 zmqstream.py:542(sending) 1 0.000 0.000 0.000 0.000 base_events.py:837(call_soon_threadsafe) 4 0.000 0.000 0.000 0.000 weakref.py:427(__setitem__) 4 0.000 0.000 0.000 0.000 queue.py:97(empty) 1 0.000 0.000 0.000 0.000 threading.py:457(__init__) 1 0.000 0.000 0.000 0.000 conf.py:202(build_args) 31 0.000 0.000 0.000 0.000 base_events.py:538(_check_closed) 1 0.000 0.000 0.000 0.000 asyncio.py:225(add_callback) 1 0.000 0.000 0.000 0.000 poll.py:80(poll) 2 0.000 0.000 0.000 0.000 typing.py:1221(__instancecheck__) 15 0.000 0.000 0.000 0.000 {built-in method _asyncio.get_running_loop} 37 0.000 0.000 0.000 0.000 {method 'popleft' of 'collections.deque' objects} 31 0.000 0.000 0.000 0.000 enum.py:1123(__new__) 1 0.000 0.000 0.000 0.000 git.py:343(__del__) 1 0.000 0.000 0.000 0.000 queues.py:225(get) 61 0.000 0.000 0.000 0.000 base_events.py:2010(get_debug) 1 0.000 0.000 0.000 0.000 concurrent.py:182(future_set_result_unless_cancelled) 15 0.000 0.000 0.000 0.000 {built-in method builtins.min} 2 0.000 0.000 0.000 0.000 typing.py:1492(__subclasscheck__) 1 0.000 0.000 0.000 0.000 selector_events.py:141(_write_to_self) 8 0.000 0.000 0.000 0.000 {method 'difference_update' of 'set' objects} 1 0.000 0.000 0.000 0.000 __init__.py:230(utcoffset) 1 0.000 0.000 0.000 0.000 {method 'send' of '_socket.socket' objects} 2 0.000 0.000 0.000 0.000 traitlets.py:676(__get__) 1 0.000 0.000 0.000 0.000 {method 'replace' of 'datetime.datetime' objects} 1 0.000 0.000 0.000 0.000 configparser.py:869(set) 2 0.000 0.000 0.000 0.000 repository.py:154(_is_remote) 1 0.000 0.000 0.000 0.000 reference.py:54(__init__) 1 0.000 0.000 0.000 0.000 conf.py:72(_check_only_one_from_commit) 1 0.000 0.000 0.000 0.000 queues.py:317(__put_internal) 4 0.000 0.000 0.000 0.000 typing.py:1285(__hash__) 1 0.000 0.000 0.000 0.000 util.py:1009(__del__) 8 0.000 0.000 0.000 0.000 {method 'partition' of 'str' objects} 2 0.000 0.000 0.000 0.000 iostream.py:216(_check_mp_mode) 2 0.000 0.000 0.000 0.000 base_events.py:1900(_add_callback) 1 0.000 0.000 0.000 0.000 queues.py:256(get_nowait) 2 0.000 0.000 0.000 0.000 abc.py:121(__subclasscheck__) 14 0.000 0.000 0.000 0.000 base_events.py:1910(_timer_handle_cancelled) 2 0.000 0.000 0.000 0.000 queues.py:322(_consume_expired) 1 0.000 0.000 0.000 0.000 reference.py:120(name) 1 0.000 0.000 0.000 0.000 conf.py:79(_check_only_one_to_commit) 2 0.000 0.000 0.000 0.000 traitlets.py:629(get) 2 0.000 0.000 0.000 0.000 iostream.py:213(_is_master_process) 4 0.000 0.000 0.000 0.000 queue.py:209(_qsize) 3 0.000 0.000 0.000 0.000 config.py:756(_assure_writable) 8 0.000 0.000 0.000 0.000 conf.py:43(set_value) 5 0.000 0.000 0.000 0.000 {method 'upper' of 'str' objects} 2 0.000 0.000 0.000 0.000 conf.py:192(only_one_filter) 1 0.000 0.000 0.000 0.000 conf.py:61(_sanity_check_repos) 2 0.000 0.000 0.000 0.000 util.py:1012(_lock_file_path) 8 0.000 0.000 0.000 0.000 {built-in method _stat.S_ISLNK} 2 0.000 0.000 0.000 0.000 {built-in method _abc._abc_subclasscheck} 1 0.000 0.000 0.000 0.000 conf.py:151(get_starting_commit) 8 0.000 0.000 0.000 0.000 util.py:1016(_has_lock) 1 0.000 0.000 0.000 0.000 {method 'reverse' of 'list' objects} 1 0.000 0.000 0.000 0.000 conf.py:175(get_ending_commit) 1 0.000 0.000 0.000 0.000 conf.py:123(_check_correct_filters_order) 1 0.000 0.000 0.000 0.000 queues.py:312(_put) 2 0.000 0.000 0.000 0.000 selectors.py:275(_key_from_fd) 1 0.000 0.000 0.000 0.000 poll.py:31(register) 4 0.000 0.000 0.000 0.000 {built-in method builtins.hash} 1 0.000 0.000 0.000 0.000 queues.py:173(qsize) 3 0.000 0.000 0.000 0.000 git.py:63(repo) 5 0.000 0.000 0.000 0.000 zmqstream.py:538(receiving) 1 0.000 0.000 0.000 0.000 {method 'isalpha' of 'str' objects} 2 0.000 0.000 0.000 0.000 {built-in method posix.getpid} 1 0.000 0.000 0.000 0.000 queues.py:309(_get) 1 0.000 0.000 0.000 0.000 configparser.py:649(has_section) 2 0.000 0.000 0.000 0.000 iostream.py:255(closed) 1 0.000 0.000 0.000 0.000 codecs.py:186(__init__) 1 0.000 0.000 0.000 0.000 pathlib.py:583(name) 1 0.000 0.000 0.000 0.000 util.py:1005(__init__) 1 0.000 0.000 0.000 0.000 unix_events.py:81(_process_self_data) 1 0.000 0.000 0.000 0.000 queues.py:177(empty) 1 0.000 0.000 0.000 0.000 base_events.py:719(is_closed) 1 0.000 0.000 0.000 0.000 {method 'isascii' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'done' of '_asyncio.Future' objects} 1 0.000 0.000 0.000 0.000 _base.py:643(__enter__) 1 0.000 0.000 0.000 0.000 zmqstream.py:659(_check_closed) 1 0.000 0.000 0.000 0.000 configparser.py:338(before_set) 1 0.000 0.000 0.000 0.000 locks.py:224(clear) 1 0.000 0.000 0.000 0.000 queues.py:59(_set_timeout) 30/0 1.924 0.064 0.000 {method 'control' of 'select.kqueue' objects} 30/0 0.002 0.000 0.000 selectors.py:558(select)
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 ifxs
is a set, but linear time ifxs
is a list; these differences become significant as the size ofxs
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:
quiz('Donald E. Knuth said: "Premature optimization..."',
[
"... is the root of all evil",
"... requires lots of experience",
"... should be left to assembly programmers",
"... is the reason why TeX is so fast",
], 'len("METAFONT") - len("TeX") - len("CWEB")')
Quiz
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
).
# ignore
from typing import Any, Optional, Type, Dict, Tuple, List
# ignore
from bookutils import print_content
# ignore
import inspect
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.
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.
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): 0.0008185830083675683, ('__init__', 19): 1.7080456018447876e-06, ('clock', 8): 1.541979145258665e-06, ('clock', 12): 1.6660196706652641e-06, ('__init__', 20): 1.7500133253633976e-06, ('remove_html_markup', 238): 0.01394206180702895, ('remove_html_markup', 239): 0.013802091707475483, ('remove_html_markup', 240): 0.013413427339401096, ('remove_html_markup', 241): 0.011729154794011265, ('remove_html_markup', 243): 0.08416594349546358, ('remove_html_markup', 244): 0.07557704375358298, ('remove_html_markup', 246): 0.07358997093979269, ('remove_html_markup', 247): 0.015421055082697421, ('remove_html_markup', 248): 0.058604994614142925, ('remove_html_markup', 250): 0.04390686209080741, ('remove_html_markup', 252): 0.0453748365980573, ('remove_html_markup', 249): 0.015190234407782555, ('remove_html_markup', 253): 0.021652915223967284, ('remove_html_markup', 255): 0.014748295943718404}
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¶
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.0003165372181683779 ('remove_html_markup', 239) 0.0002850839518941939 ('remove_html_markup', 240) 0.0002597551792860031 ('remove_html_markup', 241) 0.00023100018734112382 ('remove_html_markup', 243) 0.0016736817196942866 ('remove_html_markup', 244) 0.0014783667866140604 ('remove_html_markup', 246) 0.0014873057953082025 ('remove_html_markup', 247) 0.0002970052883028984 ('remove_html_markup', 248) 0.0011770862620323896 ('remove_html_markup', 250) 0.0008755105081945658 ('remove_html_markup', 252) 0.0008878534426912665 ('remove_html_markup', 249) 0.0002961252466775477 ('remove_html_markup', 253) 0.00043816445395350456 ('remove_html_markup', 255) 0.00029024173272773623
And we can also create a total for an entire function:
collector.total('remove_html_markup')
0.009993717772886157
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 # type: ignore
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 3% def remove_html_markup(s): # type: ignore 239 2% tag = False 240 2% quote = False 241 2% out = "" 242 0% 243 16% for c in s: 244 14% assert tag or not quote 245 0% 246 14% if c == '<' and not quote: 247 2% tag = True 248 11% elif c == '>' and not quote: 249 2% tag = False 250 8% elif (c == '"' or c == "'") and tag: 251 0% quote = not quote 252 8% elif not tag: 253 6% out = out + c 254 0% 255 2% 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.
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.30723345797741786
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&</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.
Synopsis¶
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 3% def remove_html_markup(s): # type: ignore 239 2% tag = False 240 2% quote = False 241 2% out = "" 242 0% 243 16% for c in s: 244 14% 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 2% tag = False 250 8% elif (c == '"' or c == "'") and tag: 251 0% quote = not quote 252 8% elif not tag: 253 4% out = out + c 254 0% 255 2% 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
.
# ignore
from ClassDiagram import display_class_hierarchy
# ignore
display_class_hierarchy([PerformanceDebugger, TimeCollector, HitCollector],
public_methods=[
PerformanceDebugger.__init__,
],
project='debuggingbook')
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:
tracemalloc.start()
current_size, peak_size = tracemalloc.get_traced_memory()
current_size
22923
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.