I have a Python script with a simple function. I would like to run this function 2 times, simultaneously and was wondering if this was possible.
script.py:
from multiprocessing import Process
import time
def func1():
time.sleep(1)
print('Finished sleeping')
t1_start = time.perf_counter()
p1 = Process(target=func1())
p1 = Process(target=func1())
t1_stop = time.perf_counter()
print("elapsed time: {} sec".format(round(t1_stop - t1_start), 1))
Given output:
Finished sleeping
Finished sleeping
elapsed time: 2 sec
Expected output:
Finished sleeping
Finished sleeping
elapsed time: 1 sec
I have also tried this:
from multiprocessing import Process
import time
def func1():
time.sleep(1)
print('Finished sleeping')
if __name__ == '__main__':
t1_start = time.perf_counter()
p1 = Process(target=func1) # note no ()
p2 = Process(target=func1) # note no ()
p1.start()
p2.start()
t1_stop = time.perf_counter()
print("elapsed time: {} sec".format(round(t1_stop - t1_start), 1))
However that gives this output:
elapsed time: 0 sec
Finished sleeping
Finished sleeping
Process(target=func1())executesfunc1immediately. UseProcess(target=func1)instead. Note that you muststartprocesses and shouldjointhem to see how long they run, by the way.if __name__ == "__main__":guard for starting the processes. As the error says.