Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.3 kB
4
Indexable
Never
import tracemalloc
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def profile_reverse(n):
    tracemalloc.start()
    lst = list(range(n))
    lst.reverse()
    current, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return peak/10**6

def profile_slicing(n):
    tracemalloc.start()
    lst = list(range(n))
    reversed_lst = lst[::-1]
    current, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return peak/10**6  # Return peak memory usage, size before, size after

list_lengths = [10 ** i for i in range(1, 8)]
reverse_usages = [profile_reverse(n) for n in list_lengths]
slicing_usages = [profile_slicing(n) for n in list_lengths]

df = pd.DataFrame({
    'List Length': list_lengths,
    'Memory Usage (reverse) (MB)': reverse_usages,
    'Memory Usage (slicing) (MB)': slicing_usages
})

plt.figure(figsize=(10, 6))
plt.plot(df['List Length'], df['Memory Usage (reverse) (MB)'], marker='o', label='lst.reverse()')
plt.plot(df['List Length'], df['Memory Usage (slicing) (MB)'], marker='o', label='lst[::-1]')
plt.xscale('log')
plt.xlabel('Array Length')
plt.ylabel('Memory Usage (MB)')
plt.title('Memory Usage Comparison: lst.reverse() vs. lst[::-1]')
plt.legend()
plt.grid(True)
plt.show()
Leave a Comment