I want to create a decorator that profiles a method and logs the result. How can this be done?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
I like the answer of @detly. But sometimes its a problem to use SnakeViz to view the result.
I made a slightly different version that writes the result as text to the same file:
I hope this helps someone...
Here is a decorator with two parameters, the profile output's file name, and the field to sort by the results. The default value is the cumulative time, which is useful to find bottlenecks.
The decorator would look something like:
Anyway, if you want to do some serious profiling I would suggest you use the profile or cProfile packages.
If you've understood how to write a decorator for cProfile, consider using functools.wraps.
Simply adds one line can help you debugging decorators much easier. Without the use of functools.wraps, the name of the decorated function would have been 'wrapper', and the docstring of would have been lost.
So the improved version would be
If you want proper profiling instead of timing, you can use an undocumented feature of
cProfile
(from this question):If you want more control over the file name then you will need another layer of indirection:
It looks complicated, but if you follow it step by step (and note the difference in invoking the profiler) it should become clear.