Anti-pattern: Calling ray.get in a loop harms parallelism#

Avoid calling ray.get() in a loop, because it’s a blocking call. Use ray.get() only for the final result.

A call to ray.get() fetches the results of remotely executed functions. However, it’s a blocking call, so it always waits until the requested result is available. If you call ray.get() in a loop, the loop doesn’t continue until the call to ray.get() resolves.

If you also spawn the remote function calls in the same loop, you end up with no parallelism at all. ray.get() makes you wait for the previous function call to finish, and you spawn the next call only in the next iteration of the loop. Instead, separate the call to ray.get() from the calls to the remote functions. That way, you spawn all remote functions before you wait for the results, and they can run in parallel in the background. You can also pass a list of object refs to ray.get() to wait for all of the tasks to finish, instead of calling it on each ref one by one.

Code example#

import ray

ray.init()


@ray.remote
def f(i):
    return i


# Anti-pattern: no parallelism due to calling ray.get inside of the loop.
sequential_returns = []
for i in range(100):
    sequential_returns.append(ray.get(f.remote(i)))

# Better approach: parallelism because the tasks are executed in parallel.
refs = []
for i in range(100):
    refs.append(f.remote(i))

parallel_returns = ray.get(refs)
../../_images/ray-get-loop.svg

Calling ray.get() in a loop#

When you call ray.get() right after scheduling the remote work, the loop blocks until the result arrives, so processing is sequential. Instead, schedule all remote calls first so that they run in parallel. After scheduling the work, request all the results at once.

Other anti-patterns related to ray.get() are the following: