import threading
import time
defsum(n):
sum = 0for i in range(1, n+1):
time.sleep(0.001)
sum += i
return sum
print("single thread".center(40, "#"))
s = time.time()
sum(1000)
sum(1000)
sum(1000)
interval = time.time() - s
print("single time interval: {}".format(interval))
print("multi thread".center(40, "#"))
# method 1
n = [1000, 1000, 1000]
mythread = []
s = time.time()
for i in range(len(n)):
t = threading.Thread(target=sum, args=(n[i],))
mythread.append(t)
for t in mythread:
t.start()
for t in mythread:
t.join()
interval = time.time() - s
print("multi 1 time interval: {}".format(interval))
s = time.time()
classMythread(threading.Thread):def__init__(self, func, args):
super(Mythread,self).__init__()
self.func = func
self.args = args
defrun(self):
self.func(self.args)
mythread1 = []
#mythread.clear()for i in range(len(n)):
mythread1.append(Mythread(sum, n[i]))
for i in range(len(n)):
mythread1[i].start()
for i in range(len(n)):
mythread1[i].join()
interval = time.time() - s
print("multi 2 time interval: {}".format(interval))