heartrate: Real-time Code Visualization in Python

The Problem: Manual Debugging and Print Statements

Understanding how your Python code executes in real-time and identifying performance bottlenecks can be challenging. Traditional debugging methods and print statements often clutter code and provide an incomplete picture of program flow.

Let’s consider an example of a simple factorial function with manual debugging and print statements.

def factorial(x, depth=0):
    print(f"Calculating factorial({x})")

    if x == 1:
        print(f"Base case: factorial(1) = 1")
        return 1
    else:
        result = x * factorial(x-1, depth + 1)
        print(f"factorial({x}) = {x} * factorial({x-1}) = {result}")
        return result


if __name__ == "__main__":
    num = 5
    result = factorial(num)
    print(f"The factorial of {num} is {factorial(num)}")

Output:

Calculating factorial(5)
Calculating factorial(4)
Calculating factorial(3)
Calculating factorial(2)
Calculating factorial(1)
Base case: factorial(1) = 1
factorial(2) = 2 * factorial(1) = 2
factorial(3) = 3 * factorial(2) = 6
factorial(4) = 4 * factorial(3) = 24
factorial(5) = 5 * factorial(4) = 120
Calculating factorial(5)
Calculating factorial(4)
Calculating factorial(3)
Calculating factorial(2)
Calculating factorial(1)
Base case: factorial(1) = 1
factorial(2) = 2 * factorial(1) = 2
factorial(3) = 3 * factorial(2) = 6
factorial(4) = 4 * factorial(3) = 24
factorial(5) = 5 * factorial(4) = 120
The factorial of 5 is 120

This approach results in cluttered code and repeated execution of the factorial function.

The Solution: Heartrate

Heartrate is a Python library that allows you to visualize your code execution in real time through a browser interface. It shows line execution counts, recent activity with color-coded bars, and a live stack trace without modifying your source code.

To use Heartrate, you only need to add two lines of code.

import heartrate 
heartrate.trace(browser=True)

def factorial(x):
    if x == 1:
        sleep(1)
        return 1
    else:
        sleep(1)
        return (x * factorial(x-1))


if __name__ == "__main__":
    num = 5
    print(f"The factorial of {num} is {factorial(num)}")

This will open a browser window displaying the visualization of the code execution.

The visualization consists of the following components:

  • Line hit counts on the left side
  • Visual bars showing recent line executions (longer = more hits, lighter = more recent)
  • Currently executing lines highlighted

By using heartrate, you can gain a deeper understanding of your code’s execution flow and identify performance bottlenecks without cluttering your code with print statements.

Link to heartrate.

Related Posts

Leave a Comment

Your email address will not be published. Required fields are marked *

Related Posts

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran