Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def profile_function(function, *args, **kwargs):
- """ Returns performance statistics (as a string) for the given function.
- """
- def _run():
- function(*args, **kwargs)
- import cProfile as profile
- import pstats
- import os
- import sys; sys.modules['__main__'].__profile_run__ = _run
- id = function.__name__ + '()'
- profile.run('__profile_run__()', id)
- p = pstats.Stats(id)
- p.stream = open(id, 'w')
- p.sort_stats('time').print_stats(20)
- p.stream.close()
- s = open(id).read()
- os.remove(id)
- return s
- def int_to_str_with_check(s):
- if s.isdigit():
- return int(s)
- return None
- def int_to_str_with_exception(s):
- try:
- return int(s)
- except ValueError:
- return None
- NUM_ITERATIONS = 10000000
- def test_check():
- s = '10'
- sum = 0
- for i in range(NUM_ITERATIONS):
- sum += int_to_str_with_check(s)
- return sum
- def test_exception():
- s = '10'
- sum = 0
- for i in range(NUM_ITERATIONS):
- sum += int_to_str_with_exception(s)
- return sum
- print(profile_function(test_check))
- print(profile_function(test_exception))
- python profile_books.py
- Thu Oct 18 13:16:07 2018 test_check()
- 20000005 function calls in 7.148 seconds
- Ordered by: internal time
- ncalls tottime percall cumtime percall filename:lineno(function)
- 10000000 4.054 0.000 4.850 0.000 profile_books.py:20(int_to_str_with_check)
- 1 2.298 2.298 7.148 7.148 profile_books.py:33(test_check)
- 10000000 0.796 0.000 0.796 0.000 {method 'isdigit' of 'str' objects}
- 1 0.000 0.000 7.148 7.148 {built-in method builtins.exec}
- 1 0.000 0.000 7.148 7.148 <string>:1(<module>)
- 1 0.000 0.000 7.148 7.148 profile_books.py:4(_run)
- 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
- Thu Oct 18 13:16:12 2018 test_exception()
- 10000005 function calls in 5.136 seconds
- Ordered by: internal time
- ncalls tottime percall cumtime percall filename:lineno(function)
- 10000000 2.897 0.000 2.897 0.000 profile_books.py:25(int_to_str_with_exception)
- 1 2.239 2.239 5.136 5.136 profile_books.py:40(test_exception)
- 1 0.000 0.000 5.136 5.136 {built-in method builtins.exec}
- 1 0.000 0.000 5.136 5.136 profile_books.py:4(_run)
- 1 0.000 0.000 5.136 5.136 <string>:1(<module>)
- 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement