w3resource

Python: Determine profiling of Python programs

Python Basic: Exercise-51 with Solution

Write a Python program to determine profiling of Python programs.

Note: A profile is a set of statistics that describes how often and for how long various parts of the program executed. These statistics can be formatted into reports via the pstats module.

Sample Solution:-

Python Code:

import cProfile
def sum():
    print(1+2)
cProfile.run('sum()')

Sample Output:

3                                                                                                             
         5 function calls in 0.000 seconds                                                                    
                                                                                                              
   Ordered by: standard name                                                                                  
                                                                                                              
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)                                       
        1    0.000    0.000    0.000    0.000 7aa14930-2430-11e7-807b-bd9de91b1602.py:2(sum)                  
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)                                            
        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}                                 
        1    0.000    0.000    0.000    0.000 {built-in method builtins.print}                                
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}  
	

Flowchart:

Flowchart: Determine profiling of Python programs.

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to print without newline or space?
Next: Write a Python program to print to stderr.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Try-catch-else construct:

try:
  foo() 
except Exception: 
  print("Exception occured")
else:
  print("Exception didnt occur")
finally:
  print("Always gets here")