【问题标题】:Python saving execution time when multithreadingPython在多线程时节省执行时间
【发布时间】:2015-11-22 13:28:19
【问题描述】:

我在 python 2.7 中使用多线程和使用队列时遇到问题。我希望有线程的代码大约是没有线程的代码的一半,但我认为我做错了什么。我正在对斐波那契数列使用一种简单的循环技术来最好地显示问题。

这是没有线程和队列的代码。它打印了 19.9190001488 秒作为其执行时间。

import time

start_time = time.time()

def fibonacci(priority, num):
    if num == 1 or num == 2:
        return 1
    a = 1
    b = 1
    for i in range(num-2):
        c = a + b
        b = a
        a = c
    return c

print fibonacci(0, 200000)
print fibonacci(1, 100)
print fibonacci(2, 200000)
print fibonacci(3, 2)

print("%s seconds" % (time.time() - start_time))

这是带有线程和队列的代码。它打印了 21.7269999981 秒作为其执行时间。

import time

start_time = time.time()

from Queue import *
from threading import *

numbers = [200000,100,200000,2]
q = PriorityQueue()
threads = []

def fibonacci(priority, num):
    if num == 1 or num == 2:
        q.put((priority, 1))
        return
    a = 1
    b = 1
    for i in range(num-2):
        c = a + b
        b = a
        a = c
    q.put((priority, c))
    return

for i in range(4):
    priority = i
    num = numbers[i]
    t = Thread(target = fibonacci, args = (priority, num))
    threads.append(t)

#print threads

for t in threads:
    t.start()

for t in threads:
    t.join()

while not q.empty():
    ans = q.get()
    q.task_done()
    print ans[1]

print("%s seconds" % (time.time() - start_time))

我认为会发生的是多线程代码的时间是没有线程的代码的一半。本质上我认为所有线程同时工作,因此计算斐波那契数为 200,000 的 2 个线程将同时完成,因此执行速度大约是没有线程的代码的两倍。显然这不是发生的事情。难道我做错了什么?我只想同时执行所有线程,按照它们启动的顺序打印,耗时最长的线程几乎就是执行时间。

编辑:

我更新了我的代码以使用进程,但现在没有打印结果。仅显示 0.163000106812 秒的执行时间。这是新代码:

import time

start_time = time.time()

from Queue import *
from multiprocessing import *

numbers = [200000,100,200000,2]
q = PriorityQueue()
processes = []

def fibonacci(priority, num):
    if num == 1 or num == 2:
        q.put((priority, 1))
        return
    a = 1
    b = 1
    for i in range(num-2):
        c = a + b
        b = a
        a = c
    q.put((priority, c))
    return

for i in range(4):
    priority = i
    num = numbers[i]
    p = Process(target = fibonacci, args = (priority, num))
    processes.append(p)

#print processes

for p in processes:
    p.start()

for p in processes:
    p.join()

while not q.empty():
    ans = q.get()
    q.task_done()
    print ans[1]

print("%s seconds" % (time.time() - start_time))

【问题讨论】:

  • 您使用的是哪个操作系统?窗户?

标签: python multithreading python-2.7 time queue


【解决方案1】:

您遇到了 CPython 实现的基本限制因素之一,Global Interpreter Lock 或 GIL。这有效地序列化了您的程序,您的线程将轮流执行。一个线程将拥有 GIL,而其他线程将等待 GIL 释放。

一种解决方案是使用单独的进程。每个进程都有自己的 GIL,因此可以并行执行。可能最简单的方法是使用 Python 的 multiprocessing 模块作为线程模块的替代品。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 2017-11-20
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多