1,2,3,4共4个问题,2,4是同一类型的,全部放进注释中了
本帖最后由 Boibot 于 2022-10-23 15:54 编辑import threading# 线程模块
import time
def eat_breakfast():
time.sleep(3)
print("You eat breakfast")
def drink_coffee():
time.sleep(4)
print("You drank coffee")
def study():
time.sleep(5)
print("You finish studying")
x = threading.Thread(target=eat_breakfast, args=())# 1.target=function,这里的函数加不加括号是一样的吗?
x.start()
y = threading.Thread(target=drink_coffee, args=())
y.start()
z = threading.Thread(target=study, args=())
z.start()
x.join() # thread synchronization(线程同步)
y.join() # thread synchronize and join(线程同步并加入)
z.join()
# eat_breakfast()
# drink_coffee()
# study()
print(threading.active_count())# 函数名活动计数
print(threading.enumerate())# 函数名枚举
print(time.perf_counter())# performance counter function(函数名性能计数器)
console window output:# 2.time.perf_counter()是以秒为单位,我的输出相较正确答案大了上万倍
You eat breakfast
You drank coffee
You finish studying
1
[<_MainThread(MainThread, started 14744)>]
9517.6617491
from multiprocessing import Process, cpu_count
import time
def counter(num):
count = 0
while count < num:
count += 1
def main():
print(cpu_count())
a = Process(target=counter, args=(12500000,))# 3.Process(target=counter, args=(12500000,)),Pruocess函数的args参数是元组,里面的num元素为什么必须要加","逗号
b = Process(target=counter, args=(12500000,))
c = Process(target=counter, args=(12500000,))
d = Process(target=counter, args=(12500000,))
e = Process(target=counter, args=(12500000,))
f = Process(target=counter, args=(12500000,))
g = Process(target=counter, args=(12500000,))
h = Process(target=counter, args=(12500000,))
a.start()
b.start()
c.start()
d.start()
e.start()
f.start()
g.start()
h.start()
a.join()
b.join()
c.join()
d.join()
e.join()
f.join()
g.join()
h.join()
print("Finished in", time.perf_counter(), "seconds")
if __name__ == '__main__':
main()
console window output:# 4.time.perf_counter()是以秒为单位,我的输出相较正确答案大了上万倍
16
Finished in 75426.6729955 seconds
都学到线程了, time.perf_counter() 都不会用,即使不会用,也应该会查一下文档或相关例子吧。。{:10_277:} 阿奇_o 发表于 2022-10-23 15:50
都学到线程了, time.perf_counter() 都不会用,即使不会用,也应该会查一下文档或相关例子吧。。{:10_277: ...
刚学到的,对着视频打完,发现输出跟答案对不上,找了time.perf_counter() 官方文档和一些网站的解释,并不能解释为啥我的输出是上万秒
页:
[1]