Profiling Python Code for Time and Memory Usage

Measuring Execution Time

To analyze the computational complexity of algorithms, comparing their time and memory consumption is essential. Measuring execution time in Python is straightforward using the time module's perf_counter function, which provides high-resolution timing.

import time

def compute_brb(input_data, theta, delta, beta, c):
    # Placeholder for actual computation logic
    result = []
    activation_count = 0
    # Simulated processing
    for item in input_data:
        if item > theta:
            result.append(item * delta)
            activation_count += 1
    return result, activation_count

# Define sample parameters
input_values = [i for i in range(1000)]
theta_param = 0.5
delta_param = 2.0
beta_param = 1.0
c_param = 0.1

# Start timing
timer_start = time.perf_counter()

# Execute the target function
output_result, rules_activated = compute_brb(
    input_data=input_values,
    theta=theta_param,
    delta=delta_param,
    beta=beta_param,
    c=c_param
)

# Stop timing
timer_end = time.perf_counter()

print(f'Execution duration: {timer_end - timer_start} seconds')

The output will display the elapsed time in seconds. For instance:

Execution duration: 0.000124 seconds

Measuring Memory Consumption

To profile memory usage, the memory_profiler package is commonly used. First, ensure its installed via pip:

pip install memory-profiler

Decorate the function you wish to profile with @profile.

from memory_profiler import profile

@profile
def compute_brb(input_data, theta, delta, beta, c):
    result = []
    activation_count = 0
    # Simulated memory-intensive operation
    temp_list = [i * delta for i in input_data if i > theta]
    result.extend(temp_list)
    activation_count = len(temp_list)
    return result, activation_count

# Function call with parameters
output_result, rules_activated = compute_brb(
    input_data=input_values,
    theta=theta_param,
    delta=delta_param,
    beta=beta_param,
    c=c_param
)

To run the memory profiler from with in an IDE like PyCharm, use the integrated terminal. Right-click in the code editor area and select "Open in Terminal". In the terminal, execute:

mprof run script_name.py

This command runs the script and records memory usage over time, generating a data file (typically with a .dat extension). The data can be visualized by running:

mprof plot

This generates a graph showing memory consumption during execution, allowing for analysis of memory efficiency and potential leaks.

Tags: python Profiling Memory_Profiler Performance Time_Complexity

Posted on Fri, 19 Jun 2026 18:48:56 +0000 by xenoalien