3.5 KiB
3.5 KiB
In [1]:
import numpy as np import timeit import ray # Define the expensive function @ray.remote def expensive_function(n): # Generate a large random matrix A = np.random.rand(1000, 1000) B = np.random.rand(1000, 1000) # Perform the matrix multiplication C = np.dot(A, B) # Return the result return C def expensive_function_serial(n): print(f"worker {n} started") # Generate a large random matrix A = np.random.rand(1000, 1000) B = np.random.rand(1000, 1000) # Perform the matrix multiplication C = np.dot(A, B) # Return the result print(f"worker {n} finsihed") return C # Initialize Ray ray.init() # Create 4 remote actors to distribute the work futures = [expensive_function.remote(_) for _ in range(4)] # Time the function using Ray with 4 parts start_time = timeit.default_timer() print("waiting for ray") results = ray.get(futures) print("ray returned all") end_time = timeit.default_timer() ray_time = end_time - start_time print("ray finsihed", ray_time) # Time the function serially start_time = timeit.default_timer() results = [expensive_function_serial(_) for _ in range(4)] end_time = timeit.default_timer() serial_time = end_time - start_time print("serial function finsihed", serial_time) # Print the results print(f"Ray with 4 parts: {ray_time} seconds") print(f"Serial: {serial_time} seconds") # Compare the results if ray_time < serial_time: print("Ray with 4 parts is faster than serial computation") else: print("Serial computation is faster than Ray with 4 parts") # Shutdown Ray ray.shutdown()
2024-10-03 09:43:41,741 INFO worker.py:1786 -- Started a local Ray instance.
waiting for ray ray returned all ray finsihed 0.4031927839969285 worker 0 started worker 0 finsihed worker 1 started worker 1 finsihed worker 2 started worker 2 finsihed worker 3 started worker 3 finsihed serial function finsihed 0.21200023603159934 Ray with 4 parts: 0.4031927839969285 seconds Serial: 0.21200023603159934 seconds Serial computation is faster than Ray with 4 parts