File: profiler.py

package info (click to toggle)
python-easydev 0.13.3%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 636 kB
  • sloc: python: 1,904; makefile: 116; javascript: 49
file content (70 lines) | stat: -rw-r--r-- 1,911 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# -*- python -*-
# -*- coding: utf-8 -*-
#
#  This file is part of the easydev software
#
#  Copyright (c) 2011-2024
#
#  File author(s): Thomas Cokelaer <cokelaer@gmail.com>
#
#  Distributed under the BSD3 License.
#
#  Website: https://github.com/cokelaer/easydev
#  Documentation: http://easydev-python.readthedocs.io
#
##############################################################################
"""

Usage::

    from easydev import do_profile
    @do_profile()
    def test():
        x = 1
        x *= x
        return x

# source: https://zapier.com/engineering/profiling-python-boss/


Requires line_profiler to be installed. line_profiler has C code and we wish
easydev to be as simple as possible. So, we do not want compiled code dependencies.
Consequently, we added line_profiler in the extra_requires instead of requires
in the setup.py One must install line_profiler itself.
"""

__all__ = ["do_profile"]

try:
    from line_profiler import LineProfiler

    def do_profile(follow=[]):
        def inner(func):
            def profiled_func(*args, **kwargs):
                try:
                    profiler = LineProfiler()
                    profiler.add_function(func)
                    for f in follow:
                        profiler.add_function(f)
                    profiler.enable_by_count()
                    return func(*args, **kwargs)
                finally:
                    profiler.print_stats()

            return profiled_func

        return inner

except ImportError:  # pragma: no cover

    def do_profile(follow=[]):
        "Helpful if you accidentally leave in production!"
        print("easydev warning:: line_profiler does not seem to be installed. " + "Type 'pip install line_profiler'")

        def inner(func):
            def nothing(*args, **kwargs):
                return func(*args, **kwargs)

            return nothing

        return inner