Advertisement
Guest User

Untitled

a guest
Oct 18th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. def profile_function(function, *args, **kwargs):
  2. """ Returns performance statistics (as a string) for the given function.
  3. """
  4. def _run():
  5. function(*args, **kwargs)
  6. import cProfile as profile
  7. import pstats
  8. import os
  9. import sys; sys.modules['__main__'].__profile_run__ = _run
  10. id = function.__name__ + '()'
  11. profile.run('__profile_run__()', id)
  12. p = pstats.Stats(id)
  13. p.stream = open(id, 'w')
  14. p.sort_stats('time').print_stats(20)
  15. p.stream.close()
  16. s = open(id).read()
  17. os.remove(id)
  18. return s
  19.  
  20. def int_to_str_with_check(s):
  21. if s.isdigit():
  22. return int(s)
  23. return None
  24.  
  25. def int_to_str_with_exception(s):
  26. try:
  27. return int(s)
  28. except ValueError:
  29. return None
  30.  
  31. NUM_ITERATIONS = 10000000
  32.  
  33. def test_check():
  34. s = '10'
  35. sum = 0
  36. for i in range(NUM_ITERATIONS):
  37. sum += int_to_str_with_check(s)
  38. return sum
  39.  
  40. def test_exception():
  41. s = '10'
  42. sum = 0
  43. for i in range(NUM_ITERATIONS):
  44. sum += int_to_str_with_exception(s)
  45. return sum
  46.  
  47.  
  48. print(profile_function(test_check))
  49. print(profile_function(test_exception))
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56. python profile_books.py
  57. Thu Oct 18 13:16:07 2018 test_check()
  58.  
  59. 20000005 function calls in 7.148 seconds
  60.  
  61. Ordered by: internal time
  62.  
  63. ncalls tottime percall cumtime percall filename:lineno(function)
  64. 10000000 4.054 0.000 4.850 0.000 profile_books.py:20(int_to_str_with_check)
  65. 1 2.298 2.298 7.148 7.148 profile_books.py:33(test_check)
  66. 10000000 0.796 0.000 0.796 0.000 {method 'isdigit' of 'str' objects}
  67. 1 0.000 0.000 7.148 7.148 {built-in method builtins.exec}
  68. 1 0.000 0.000 7.148 7.148 <string>:1(<module>)
  69. 1 0.000 0.000 7.148 7.148 profile_books.py:4(_run)
  70. 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
  71.  
  72.  
  73.  
  74. Thu Oct 18 13:16:12 2018 test_exception()
  75.  
  76. 10000005 function calls in 5.136 seconds
  77.  
  78. Ordered by: internal time
  79.  
  80. ncalls tottime percall cumtime percall filename:lineno(function)
  81. 10000000 2.897 0.000 2.897 0.000 profile_books.py:25(int_to_str_with_exception)
  82. 1 2.239 2.239 5.136 5.136 profile_books.py:40(test_exception)
  83. 1 0.000 0.000 5.136 5.136 {built-in method builtins.exec}
  84. 1 0.000 0.000 5.136 5.136 profile_books.py:4(_run)
  85. 1 0.000 0.000 5.136 5.136 <string>:1(<module>)
  86. 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