CodeBlanks Logo Icon CodeBlanks

cProfile

Learn to profile with cProfile.

What is cProfile?

The cProfile module shows where a program spends its time. You create a profile object with cProfile.Profile().

pr.enable() starts measurement and pr.disable() stops it. The code between is profiled. You print results with pr.print_stats() or sort them with the pstats module. This is the standard way to find performance hotspots. To see which function is slow you first find the one that takes the most time.

The profiling flow

The typical profiling flow is: create a Profile(), call enable(), run the code to measure, call disable(), examine results.

This flow lets you measure only the section you care about. For example you can profile a loop and skip the rest. The print_stats() output gives call count, total time and average time for each function. The function taking the most time appears at the top; this is called a hotspot. You start optimization there.

Practice Profile with cProfile

Import the module with import cProfile. Create a profile object with pr = cProfile.Profile(). Call pr.enable(), do total = sum(range(100)), call pr.disable(). Write print("profil alindi").

Starter code

main.py
# create a profile object
# measure and stop
# print a fixed message

Sample solution

main.py
import cProfile

pr = cProfile.Profile()
pr.enable()
total = sum(range(100))
pr.disable()
print("profiled")

Expected output

profil alindi

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is cProfile for?

  • Measures memory usage
  • Monitors network traffic
  • Returns file size
  • Profiles function times Correct answer

Explanation: cProfile profiles function times; it finds bottlenecks.

2 Complete the cProfile definition

Question
import cProfile

pr = cProfile.____()
Answer
import cProfile

pr = cProfile.Profile()

Explanation: cProfile.Profile() creates a profile object.

3 Match cProfile concepts

Term Meaning
Profile Profile object
enable Starts measurement
disable Stops measurement
hotspot Bottleneck

All lessons in Expert