Difference between numpy array and list 

To compare the difference in time and memory usage between NumPy arrays and Python lists, we'll create a program that performs basic arithmetic operations on both data structures. We'll measure the execution time and memory usage using the time and memory_profiler modules in Python. First, make sure you have the numpy package and memory-profiler module installed. If you don't have them, you can install them using the following commands:

pip install numpy

pip install memory-profiler

 

import numpy as np

import time

from memory_profiler import profile


@profile

def numpy_array_operations():

    # Create a NumPy array

    arr = np.arange(1, 1000000)


    # Perform basic arithmetic operations

    sum_result = np.sum(arr)

    mul_result = arr * 2


@profile

def python_list_operations():

    # Create a Python list

    lst = list(range(1, 1000000))


    # Perform basic arithmetic operations

    sum_result = sum(lst)

    mul_result = [x * 2 for x in lst]


if __name__ == "__main__":

    print("Time and Memory Usage Comparison:")

    

    # Measure time and memory usage for NumPy array operations

    print("\nNumPy Array Operations:")

    start_time = time.time()

    numpy_array_operations()

    end_time = time.time()

    print(f"Time taken: {end_time - start_time:.6f} seconds")


    # Measure time and memory usage for Python list operations

    print("\nPython List Operations:")

    start_time = time.time()

    python_list_operations()

    end_time = time.time()

    print(f"Time taken: {end_time - start_time:.6f} seconds")

 

No comments:

Post a Comment