Login

decorator for runsnake

Author:
peiwei
Posted:
November 19, 2014
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)
  1. Add this decorator to whatever function: @profile('/tmp/0123test.prof') def test_function(): pass
  2. If it's a django view function, let it run once.
  3. Use "runsnake" to open the ".prof" file. Sweet.
 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
def profile(log_file, sort='cumulative', strip_dirs=False):
    """A decorator which profiles a callable, or a view function, etc.
    Example usage:

    >>> @profile('/tmp/file_name')
        def factorial(n):
            n = abs(int(n))
            if n < 1:
                    n = 1
            x = 1
            for i in range(1, n + 1):
                    x = i * x
            return x
    ...
    """
    def outer(fun):
        import cProfile
        import tempfile
        import os

        try:
            PROFILE_LOG_BASE = '/tmp'
        except:
            PROFILE_LOG_BASE = tempfile.gettempdir()

        def inner(*args, **kwargs):
            file_name = os.path.join(PROFILE_LOG_BASE, log_file)
            file = open(file_name,"w")
            prof = cProfile.Profile()
            try:
                ret = prof.runcall(fun, *args, **kwargs)
            except:
                file.close()
                raise

            prof.dump_stats(file_name)
            file.close()
            return ret
        return inner

    # in case this is defined as "@profile" instead of "@profile()"
    if hasattr(sort, '__call__'):
        fun = sort
        sort = 'cumulative'
        outer = outer(fun)
    return outer

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.