| 1 |
.. _performance-tips: |
| 2 |
|
| 3 |
Performance tips and tricks |
| 4 |
=========================== |
| 5 |
|
| 6 |
Performance optimization is part art, part science. Just using mypyc |
| 7 |
in a simple manner will likely make your code faster, but squeezing |
| 8 |
the most performance out of your code requires the use of some |
| 9 |
techniques we'll summarize below. |
| 10 |
|
| 11 |
Profiling |
| 12 |
--------- |
| 13 |
|
| 14 |
If you are speeding up existing code, understanding where time is |
| 15 |
spent is important. Mypyc speeds up code that you compile. If most of |
| 16 |
the time is spent elsewhere, you may come back disappointed. For |
| 17 |
example, if you spend 40% of time outside compiled code, even if |
| 18 |
compiled code would go 100x faster, overall performance will only be |
| 19 |
2.5x faster. |
| 20 |
|
| 21 |
A simple (but often effective) approach is to record the time in |
| 22 |
various points of program execution using ``time.time()``, and to |
| 23 |
print out elapsed time (or to write it to a log file). |
| 24 |
|
| 25 |
The stdlib modules ``profile`` and ``cProfile`` can provide much more |
| 26 |
detailed data. (But these only work well with non-compiled code.) |
| 27 |
|
| 28 |
Avoiding slow libraries |
| 29 |
----------------------- |
| 30 |
|
| 31 |
If profiling indicates that a lot of time is spent in the stdlib or |
| 32 |
third-party libraries, you still have several options. |
| 33 |
|
| 34 |
First, if most time is spent in a few library features, you can |
| 35 |
perhaps easily reimplement them in type-annotated Python, or extract |
| 36 |
the relevant code and annotate it. Now it may be easy to compile this |
| 37 |
code to speed it up. |
| 38 |
|
| 39 |
Second, the :doc:`librt <librt>` package provides optimized |
| 40 |
alternatives for certain standard library features that are designed |
| 41 |
for mypyc-compiled code. |
| 42 |
|
| 43 |
Third, you may be able to avoid the library altogether, or use an |
| 44 |
alternative, more efficient library to achieve the same purpose. |
| 45 |
|
| 46 |
Type annotations |
| 47 |
---------------- |
| 48 |
|
| 49 |
As discussed earlier, type annotations are key to major performance |
| 50 |
gains. You should at least consider adding annotations to any |
| 51 |
performance-critical functions and classes. It may also be helpful to |
| 52 |
annotate code called by this code, even if it's not compiled, since |
| 53 |
this may help mypy infer better types in the compile code. If you use |
| 54 |
libraries, ensure they have stub files with decent type annotation |
| 55 |
coverage. Writing a stub file is often easy, and you only need to |
| 56 |
annotate features you use a lot. |
| 57 |
|
| 58 |
If annotating external code or writing stubs feel too burdensome, a |
| 59 |
simple workaround is to annotate variables explicitly. For example, |
| 60 |
here we call ``acme.get_items()``, but it has no type annotation. We |
| 61 |
can use an explicit type annotation for the variable to which we |
| 62 |
assign the result:: |
| 63 |
|
| 64 |
import acme |
| 65 |
|
| 66 |
def work() -> None: |
| 67 |
# Annotate "items" to help mypyc |
| 68 |
items: list[tuple[int, str]] = acme.get_items() |
| 69 |
for item in items: |
| 70 |
... # Do some work here |
| 71 |
|
| 72 |
Without the annotation on ``items``, the type would be ``Any`` (since |
| 73 |
``acme`` has no type annotation), resulting in slower, generic |
| 74 |
operations being used later in the function. |
| 75 |
|
| 76 |
Avoiding slow Python features |
| 77 |
----------------------------- |
| 78 |
|
| 79 |
Mypyc can optimize some features more effectively than others. Here |
| 80 |
the difference is sometimes big -- some things only get marginally |
| 81 |
faster at best, while others can get 10x faster, or more. Avoiding |
| 82 |
these slow features in performance-critical parts of your code can |
| 83 |
help a lot. |
| 84 |
|
| 85 |
These are some of the most important things to avoid: |
| 86 |
|
| 87 |
* Using class decorators or metaclasses in compiled code (that aren't |
| 88 |
properly supported by mypyc) |
| 89 |
|
| 90 |
* Heavy reliance on interpreted Python libraries (C extensions are |
| 91 |
usually fine) |
| 92 |
|
| 93 |
These things also tend to be relatively slow: |
| 94 |
|
| 95 |
* Using Python classes and instances of Python classes (native classes |
| 96 |
are much faster) |
| 97 |
|
| 98 |
* Calling decorated functions (``@property``, ``@staticmethod``, and |
| 99 |
``@classmethod`` are special cased and thus fast) |
| 100 |
|
| 101 |
* Calling nested functions |
| 102 |
|
| 103 |
* Calling functions or methods defined in other compilation units |
| 104 |
|
| 105 |
* Using ``*args`` or ``**kwargs`` |
| 106 |
|
| 107 |
* Using generator functions |
| 108 |
|
| 109 |
* Using callable values (i.e. not leveraging early binding to call |
| 110 |
functions or methods) |
| 111 |
|
| 112 |
Nested functions can often be replaced with module-level functions or |
| 113 |
methods of native classes. |
| 114 |
|
| 115 |
Callable values and nested functions can sometimes be replaced with an |
| 116 |
instance of a native class with a single method only, such as |
| 117 |
``call(...)``. You can derive the class from an ABC, if there are |
| 118 |
multiple possible functions. |
| 119 |
|
| 120 |
.. note:: |
| 121 |
|
| 122 |
Some slow features will likely get efficient implementations in the |
| 123 |
future. You should check this section every once in a while to see |
| 124 |
if some additional operations are fast. |
| 125 |
|
| 126 |
Using fast native features |
| 127 |
-------------------------- |
| 128 |
|
| 129 |
Some native operations are particularly quick relative to the |
| 130 |
corresponding interpreted operations. Using them as much as possible |
| 131 |
may allow you to see 10x or more in performance gains. |
| 132 |
|
| 133 |
Some things are not much (or any) faster in compiled code, such as set |
| 134 |
math operations. In contrast, calling a method of a native class is |
| 135 |
much faster in compiled code. |
| 136 |
|
| 137 |
If you are used to optimizing for CPython, you might have replaced |
| 138 |
some class instances with dictionaries, as they can be |
| 139 |
faster. However, in compiled code, this "optimization" would likely |
| 140 |
slow down your code. |
| 141 |
|
| 142 |
Similarly, caching a frequently called method in a local variable can |
| 143 |
help in CPython, but it can slow things down in compiled code, since |
| 144 |
the code won't use :ref:`early binding <early-binding>`:: |
| 145 |
|
| 146 |
def squares(n: int) -> list[int]: |
| 147 |
a = [] |
| 148 |
append = a.append # Not a good idea in compiled code! |
| 149 |
for i in range(n): |
| 150 |
append(i * i) |
| 151 |
return a |
| 152 |
|
| 153 |
Here are examples of features that are fast, in no particular order |
| 154 |
(this list is *not* exhaustive): |
| 155 |
|
| 156 |
* Calling compiled functions directly defined in the same compilation |
| 157 |
unit (with positional and/or keyword arguments) |
| 158 |
|
| 159 |
* Calling methods of native classes defined in the same compilation |
| 160 |
unit (with positional and/or keyword arguments) |
| 161 |
|
| 162 |
* Many :ref:`integer operations <int-ops>` |
| 163 |
|
| 164 |
* Many :ref:`float operations <float-ops>` |
| 165 |
|
| 166 |
* Booleans |
| 167 |
|
| 168 |
* :ref:`Native list operations <list-ops>`, such as indexing, |
| 169 |
``append``, and list comprehensions |
| 170 |
|
| 171 |
* While loops |
| 172 |
|
| 173 |
* For loops over ranges and lists, and with ``enumerate`` or ``zip`` |
| 174 |
|
| 175 |
* Reading dictionary items |
| 176 |
|
| 177 |
* ``isinstance()`` checks against native classes and instances of |
| 178 |
primitive types (and unions of them) |
| 179 |
|
| 180 |
* Accessing local variables |
| 181 |
|
| 182 |
* Accessing attributes of native classes |
| 183 |
|
| 184 |
* Accessing final module-level attributes |
| 185 |
|
| 186 |
* Comparing strings for equality |
| 187 |
|
| 188 |
* All features in the :doc:`librt <librt>` package, which are optimized |
| 189 |
for compiled code |
| 190 |
|
| 191 |
These features are also fast, but somewhat less so (relative to other |
| 192 |
related operations): |
| 193 |
|
| 194 |
* Constructing instances of native classes |
| 195 |
|
| 196 |
* Constructing dictionaries |
| 197 |
|
| 198 |
* Setting dictionary items |
| 199 |
|
| 200 |
* Native :ref:`dict <dict-ops>` and :ref:`set <set-ops>` operations |
| 201 |
|
| 202 |
* Native :ref:`str <str-ops>` and :ref:`bytes <bytes-ops>` operations |
| 203 |
|
| 204 |
* Accessing module-level variables |
| 205 |
|
| 206 |
Generally anything documented as a native operation is fast, even if |
| 207 |
it's not explicitly mentioned here |
| 208 |
|
| 209 |
Adjusting garbage collection |
| 210 |
---------------------------- |
| 211 |
|
| 212 |
Compilation does not speed up cyclic garbage collection. If everything |
| 213 |
else gets much faster, it's possible that garbage collection will take |
| 214 |
a big fraction of time. You can use ``gc.set_threshold()`` to adjust |
| 215 |
the garbage collector to run less often:: |
| 216 |
|
| 217 |
import gc |
| 218 |
|
| 219 |
# Spend less time in gc; do this before significant computation |
| 220 |
gc.set_threshold(150000) |
| 221 |
|
| 222 |
... # Actual work happens here |
| 223 |
|
| 224 |
Fast interpreter shutdown |
| 225 |
------------------------- |
| 226 |
|
| 227 |
If you allocate many objects, it's possible that your program spends a |
| 228 |
lot of time cleaning up when the Python runtime shuts down. Mypyc |
| 229 |
won't speed up the shutdown of a Python process much. |
| 230 |
|
| 231 |
You can call ``os._exit(code)`` to immediately terminate the Python |
| 232 |
process, skipping normal cleanup. This can give a nice boost to a |
| 233 |
batch process or a command-line tool. |
| 234 |
|
| 235 |
.. note:: |
| 236 |
|
| 237 |
This can be dangerous and can lose data. You need to ensure |
| 238 |
that all streams are flushed and everything is otherwise cleaned up |
| 239 |
properly. |
| 240 |
|
| 241 |
Work smarter |
| 242 |
------------ |
| 243 |
|
| 244 |
Usually there are many things you can do to improve performance, even |
| 245 |
if most tweaks will yield only minor gains. The key to being effective |
| 246 |
is to focus on things that give a large gain with a small effort. |
| 247 |
|
| 248 |
For example, low-level optimizations, such as avoiding a nested |
| 249 |
function, can be pointless, if you could instead avoid a metaclass -- |
| 250 |
to allow a key class to be compiled as a native class. The latter |
| 251 |
optimization could speed up numerous method calls and attribute |
| 252 |
accesses, just like that. |