I want to execute the following two functions at exactly the same time.
from multiprocessing import Process
import os
import datetime
def func_1(title):
now = datetime.datetime.now()
print "hello, world"
print "Current second: %d" % now.second
print "Current microsecond: %d" % now.microsecond
def func_2(name):
func_1('function func_2')
now = datetime.datetime.now()
print "Bye, world"
print "Current second: %d" % now.second
print "Current microsecond: %d" % now.microsecond
if __name__ == '__main__':
p = Process(target=func_2, args=('bob',))
p.start()
p.join()
And I am getting a difference in microseconds. Is there any way to execute both at the exact same time? Any help would be appreciated.
CPython
is inherently single threaded (Google "Global Interpreter Lock"). To have even a theoretical chance you would need a multicore processor, but even then only an operating system operating at a very low level could do it and even then you would need special hardware.. What you are asking for is, in any practical sense, impossible.On the computer the following was written on, this code consistently prints out the same timestamps:
This is (1) generally impossible (the "exact" part) and (2) not something that Python is good at. If you really need microsecond execution precision, use C or ASM, but an even closer way than COpython's answer would be busy-waiting in two different processes for an agreed start time:
I am not sure if this will execute at exactly the same time, but I think that it will get you closer.