多线程的鸡肋

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from contextlib import contextmanager
import time

## 因为GIL锁的原因,多线程并没有多少用
## 不适合计算密集型
@contextmanager
def _cost_time():
start_time = time.time()
print('start time : ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
yield
end_time = time.time()
seconds = end_time - start_time
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
print('end time : ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print('time cost %d:%02d:%02d ' % (h, m, s))


def decrement(n):
while n > 0:
n -= 1

# Single thread

with _cost_time():
decrement(100000000)

#
import threading
with _cost_time():
t1 = threading.Thread(target=decrement,args=[50000000])
t2 = threading.Thread(target=decrement,args=[50000000])
t1.start()
t2.start()
t1.join()
t2.join()

修改一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import time

## 因为GIL锁的原因,多线程并没有多少用
## 不适合计算密集型



def _cost_time(func):
def warpper(*args,**kw):
start_time = time.time()
print('start time : ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
func(*args,**kw)
end_time = time.time()
seconds = end_time - start_time
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
print('end time : ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print('time cost %d:%02d:%02d ' % (h, m, s))
return warpper

@_cost_time
def decrement(n):
while n > 0:
n -= 1

# Single thread
decrement(100000000)

# Multithreading
import threading
t1 = threading.Thread(target=decrement,args=[50000000])
t2 = threading.Thread(target=decrement,args=[50000000])
t1.start()
t2.start()
t1.join()
t2.join()