Advertisement
here2share

# dot_product_timeit.py

Feb 23rd, 2025 (edited)
221
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.54 KB | None | 0 0
  1. # dot_product_timeit.py
  2.  
  3. import timeit
  4.  
  5. # Simulate large image data for image enhancing (e.g., 5 million pixel values)... or even whatever training
  6. vector_size = 5000000  # Adjust based on your system's capability
  7. vector1 = [i % 256 for i in range(vector_size)]  # Pixel values 0-255
  8. vector2 = [(i + 50) % 256 for i in range(vector_size)]  # Offset pixel values
  9.  
  10. # Dot product implementation using generator and zip
  11. def dot_product(A, B):
  12.     return sum(a * b for a, b in zip(A, B))
  13.  
  14. # Basic arithmetic implementation with indexed loop
  15. def basic_arithmetic(A, B):
  16.     result = 0
  17.     for i in range(len(A)):
  18.         result += A[i] * B[i]
  19.     return result
  20.  
  21. result_dot = dot_product(vector1, vector2)
  22. result_basic = basic_arithmetic(vector1, vector2)
  23.  
  24. if result_dot == result_basic:
  25.     print("Results are equal. Waiting for timeit comparison...")
  26. else:
  27.     print("Results are NOT equal. Quitting...")
  28.     0/0
  29.  
  30. def run_dot_product():
  31.     dot_product(vector1, vector2)
  32.  
  33. def run_basic_arithmetic():
  34.     basic_arithmetic(vector1, vector2)
  35.  
  36. # Performance comparison with reduced iterations for large data
  37. test_runs = 10  # Reduced due to large vector size
  38. dot_time = timeit.timeit(run_dot_product, number=test_runs)
  39. basic_time = timeit.timeit(run_basic_arithmetic, number=test_runs)
  40.  
  41. print(f"Performance comparison for {vector_size} elements ({test_runs} runs):")
  42. print(f"Dot Product (optimized): {dot_time:.3f} seconds")
  43. print(f"Basic Arithmetic (loop): {basic_time:.3f} seconds")
  44. print(f"Dot Product was {basic_time/dot_time:.3f}x faster")
Advertisement
Comments
  • # text 0.44 KB | 1 0
    1. import numpy as np
    2. import timeit
    3.  
    4. vector_size = 1000000
    5. # Create NumPy arrays directly for better performance.
    6. vector1 = np.arange(vector_size, dtype=np.int32) % 256
    7. vector2 = (np.arange(vector_size, dtype=np.int32) + 50) % 256
    8.  
    9. def run_numpy_dot():
    10. np.dot(vector1, vector2)
    11.  
    12. # Time the NumPy dot product
    13. test_runs = 10
    14. numpy_time = timeit.timeit(run_numpy_dot, number=test_runs)
    15. print(f"NumPy dot product: {numpy_time:.3f} seconds")
    16.  
Add Comment
Please, Sign In to add comment
Advertisement