How to Run Python Functions in Parallel Using Ray API

Build distributed applications

sudo pip3 install Ray
#!/usr/bin/env python3
import ray
@ray.remote
def func1():
from datetime import datetime
import time
now = datetime.now()
current_time = now.strftime(“%H:%M:%S”)
print(“func 1 Start Time =”, current_time)
time.sleep(2)
now = datetime.now()
current_time = now.strftime(“%H:%M:%S”)
print(“func 1 End Time =”, current_time)
@ray.remote
def func2():
from datetime import datetime
import time
now = datetime.now()
current_time = now.strftime(“%H:%M:%S”)
print(“func 2 Start Time =”, current_time)
time.sleep(2)
now = datetime.now()
current_time = now.strftime(“%H:%M:%S”)
print(“func 2 End Time =”, current_time)
if __name__ == ‘__main__’:
ray.init()
ray.get([func1.remote(), func2.remote()])
view rawray hosted with ❤ by GitHub
./test1.py
(func2 pid=1596) func 2 Start Time = 11:51:48
(func1 pid=1591) func 1 Start Time = 11:51:48
(func2 pid=1596) func 2 End Time = 11:51:50
(func1 pid=1591) func 1 End Time = 11:51:50
#!/usr/bin/env python3
import ray
@ray.remote
def func1(x):
return x+1
@ray.remote
def func2(y):
return y+1
if __name__ == ‘__main__’:
ray.init()
ret1, ret2 = ray.get([func1.remote(x=2), func2.remote(y=2)])
print(ret1)
print(ret2)
#!/usr/bin/env python3
import ray
@ray.remote
def func1(x):
return x+1
@ray.remote
def func2(y):
return y+1
if __name__ == ‘__main__’:
ray.init()
funcs = []
funcs.append(func1.remote(x=2))
funcs.append(func2.remote(y=2))
results = ray.get(funcs)
print(results)
Exit mobile version