鱼C论坛

 找回密码
 立即注册
查看: 2634|回复: 2

1,2,3,4共4个问题,2,4是同一类型的,全部放进注释中了

[复制链接]
发表于 2022-10-23 15:44:06 | 显示全部楼层 |阅读模式
1鱼币
本帖最后由 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


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-10-23 15:50:14 | 显示全部楼层
都学到线程了, time.perf_counter() 都不会用,即使不会用,也应该会查一下文档或相关例子吧。。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-10-23 15:58:55 | 显示全部楼层
阿奇_o 发表于 2022-10-23 15:50
都学到线程了, time.perf_counter() 都不会用,即使不会用,也应该会查一下文档或相关例子吧。。{:10_277: ...

刚学到的,对着视频打完,发现输出跟答案对不上,找了time.perf_counter() 官方文档和一些网站的解释,并不能解释为啥我的输出是上万秒
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-25 23:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表