script.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env python
  2. # File: script.py
  3. # Name: D.Saravanan
  4. # Date: 04/05/2022
  5. """ Script to compare CPU vs. GPU """
  6. import numpy as np
  7. import cupy as cp
  8. from time import time
  9. def benchmark_processor(arr, func, argument):
  10. """ function that is going to be used for benchmarking """
  11. start_time = time()
  12. func(arr, argument)
  13. final_time = time()
  14. elapsed_time = final_time - start_time
  15. return elapsed_time
  16. # load a matrix to global memory
  17. array_cpu = np.random.randint(0, 255, size=(9999, 9999))
  18. # load the same matrix to GPU memory
  19. array_gpu = cp.asarray(array_cpu)
  20. # benchmark matrix addition on CPU by using NumPy addition function
  21. cpu_time = benchmark_processor(array_cpu, np.add, 999)
  22. # you need to run a pilot iteration on GPU first to compile and cache the function kernel on GPU
  23. benchmark_processor(array_gpu, cp.add, 1)
  24. # benchmark matrix addition on GPU by using CuPy addition function
  25. gpu_time = benchmark_processor(array_gpu, cp.add, 999)
  26. # determine how much is GPU faster
  27. processor = abs((gpu_time - cpu_time)/gpu_time) * 100
  28. print(f"CPU time: {cpu_time} seconds\nGPU time: {gpu_time} seconds\nGPU was {processor} percent faster")