Python: Determine profiling of Python programs
Python Basic: Exercise-51 with Solution
Write a Python program to determine the 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}
Explanation:
cProfile provide deterministic profiling of Python programs. A profile is a set of statistics that describes how often and for how long various parts of the program executed.profile.run(command, filename=None, sort=- 1): This function takes a single argument that can be passed to the exec() function, and an optional file name.
The above Python code imports the cProfile module. The sum() function defined in the code adds the numbers 1 and 2 and prints the result to the console using the print() function.
The cProfile.run() function is used to profile the execution of the sum() function. The run() function takes a string as its parameter that represents the code to be executed and profiled. In this case, it is passed the function call sum() as a string.
Flowchart:

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 Programming skills with w3resource's quiz.
Python: Tips of the Day
Get Current Process Id:
import os os.getpid()
21423
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook