Profiling your code (Intermediate)

Performance is important for games, luckily there are many Python profiling tools. Profiling is about building a profile of a software program in order to collect information about memory usage or time complexity.

cProfile is a C extension introduced in Python 2.5. It can be used for deterministic profiling. Deterministic profiling means that the time measurements are precise and no sampling is used. Contrast this with statistical profiling, where measurements come from random samples.

How to do it...

The following steps will help you profile your code:

  1. Creating a profile file: We will profile the collision demo code and store the profile output in a file as follows:
    python -m cProfile -o collision_demo.profile collision_demo.py
  2. The pstats browser: After creating the file, we can view and sort the data in a special command-line browser:
    python -m pstats collision_demo.profile 
    Welcome to the profile statistics browser.
    
  3. Getting help: Being able to get help is always a good thing, just type the following commands at the command line:
    collision_demo.profile% help
    
    Documented commands (type help <topic>):
    ========================================
    EOF  add  callees  callers  help  quit  read  reverse  sort  stats  strip
    
  4. Sorting: We can sort with the following sort command:
    collision_demo.profile% sort
    Valid sort keys (unique prefixes are accepted):
    stdname -- standard name
    nfl -- name/file/line
    pcalls -- call count
    file -- file name
    calls -- call count
    time -- internal time
    line -- line number
    cumulative -- cumulative time
    module -- file name
    name -- function name
    
  5. Top 3 called functions: We can get the top 3 called functions by sorting and calling stats:
    collision_demo.profile% sort calls
    collision_demo.profile% stats 3
    
             380943 function calls (380200 primitive calls) in 18.056 seconds
    
       Ordered by: call count
       List reduced from 801 to 3 due to restriction <3>
    
       ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        52156    0.013    0.000    0.013    0.000 {method 'endswith' of 'str' objects}
    31505/31368    0.003    0.000    0.003    0.000 {len}
        27573    0.022    0.000    0.022    0.000 {method 'lower' of 'str' objects}
    

How it works...

We profiled the collision demo. The following table summarizes the profiler output:

Column

Description

Ncalls

Number of calls

Tottime

Total time spent in a function

Percall

Time per call, calculated by dividing the total time by the calls count

Cumtime

Cumulative time spent in function and functions called by the function, including recursive calls

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset