Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python concurrent.futures性能差异不大_Python_Multithreading_Concurrent.futures - Fatal编程技术网

Python concurrent.futures性能差异不大

Python concurrent.futures性能差异不大,python,multithreading,concurrent.futures,Python,Multithreading,Concurrent.futures,我得到了以下代码: from concurrent.futures import ThreadPoolExecutor, wait import datetime def calculate_mass(mass): for _ in range(10000): gravity = 9.8 weight = mass * gravity def perform_calculations(): with ThreadPoolExecutor(3)

我得到了以下代码:

from concurrent.futures import ThreadPoolExecutor, wait
import datetime

def calculate_mass(mass):
    for _ in range(10000):
        gravity = 9.8
        weight = mass * gravity


def perform_calculations():
    with ThreadPoolExecutor(3) as pool:
        pool.map(calculate_mass, range(1000))

if __name__ == '__main__':
    start = datetime.datetime.now()
    perform_calculations()
    end = datetime.datetime.now()

    print((end - start).total_seconds())
使用8gb ram(dell笔记本电脑)在第三代core i7上执行需要1.6467秒

如果更改此行的

weight = mass * gravity

突然之间,需要0.059083秒才能完成

有人知道为什么会这样吗

编辑:我想我累了。我没有注意到循环正在结束。我的坏蛋们

用这句台词:

for _ in range(10000):
    gravity = 9.8
    weight = mass * gravity
它在for循环中迭代10000次。这需要时间

但是,当您将其更改为:

for _ in range(10000):
    gravity = 9.8
    return mass * gravity

在for循环中只进行1次迭代后,它将返回mass*gravity的值。

为什么要导入concurrent.futures“wait”?这是因为您只运行一个循环,然后返回而不是10000个循环。
for _ in range(10000):
    gravity = 9.8
    return mass * gravity