Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.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

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多核比单核慢_Python_Multithreading_Performance_Primes_Single Threaded - Fatal编程技术网

Python多核比单核慢

Python多核比单核慢,python,multithreading,performance,primes,single-threaded,Python,Multithreading,Performance,Primes,Single Threaded,我试图比较单线程和多线程的性能,并编写了素数检查器 它只有两个函数,一个在正常的单线程模式下运行,另一个使用python并发模块并尝试将一组进程排队以检查一个数字是否为素数 问题是,它在单线程模式下的工作速度要比在多线程模式下快得多 这是我的密码: import time, os, math, threading from concurrent import futures N = 1000 pList = [] pListM = [] processes = [] ex = future

我试图比较单线程和多线程的性能,并编写了素数检查器

它只有两个函数,一个在正常的单线程模式下运行,另一个使用python并发模块并尝试将一组进程排队以检查一个数字是否为素数

问题是,它在单线程模式下的工作速度要比在多线程模式下快得多

这是我的密码:

import time, os, math, threading
from concurrent import futures

N = 1000

pList = []
pListM = []

processes = []
ex = futures.ProcessPoolExecutor()

def isPrime(n):
    if n < 2:
        return (n,False)
    if n == 2:
        return (n,True)
    if n % 2 == 0:
        return (n,False)

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return (n,False)
    return (n,True)

def firstPrimes(n):
        initTime = time.perf_counter()
        global pList
        i = 0
        while len(pList) < n:
                if isPrime(i): 
                        pList.append(i)
                i = i+1
        totalTime = time.perf_counter() - initTime
        print(pList)
        print("Single-Threaded it took ",totalTime," seconds to find the first ",N," primes.")

def done(fn):
    global N
    if fn.cancelled():
        print('{}: canceled'.format(fn))
    elif fn.done():
        error = fn.exception()
        if error:
            print('{}: error returned: {}'.format(
                fn.arg, error))
        else:
            result = fn.result()
##            print("\nEl resultado fue ",result,"\n")
##            print("Will pop index: ", result[0])
            processes.remove([result[0],fn])
            if result[1] and len(pListM) < N:
                    pListM.append(result[0])
##                    print("La lista de primos es: ",pListM)


def firstPrimesM(n):
        initTime = time.perf_counter()
        global pListM
        global processes
        global ex
        i = 0

        while len(pListM) < n:
                if len(processes) < 16:
##                        print("submiting process ",i)
                        pro = ex.submit(isPrime, i)
                        pro.add_done_callback(done)
                        processes.append([i,pro])
##                        print(processes)
                        i = i + 1
        for i, pro in reversed(processes):
                if not pro.cancel():
                        print('did not cancel {}'.format(i))
        ex.shutdown()
        totalTime = time.perf_counter() - initTime
        print(pListM)
        print("Multi-Threaded it took ",totalTime," seconds to find the first ",N," primes.")

if __name__ == '__main__':
        try:
                firstPrimes(N)
                firstPrimesM(N)
        except KeyboardInterrupt:
            print("User exited with Ctrl + C")
            for i, pro in reversed(processes):
                if not pro.cancel():
                        print('did not cancel {}'.format(i))
            ex.shutdown()
导入时间、操作系统、数学、线程
从同步进口期货
N=1000
pList=[]
pListM=[]
进程=[]
ex=futures.ProcessPoolExecutor()
def iPrime(n):
如果n<2:
返回(n,False)
如果n==2:
返回(n,True)
如果n%2==0:
返回(n,False)
sqrt_n=int(math.floor(math.sqrt(n)))
对于范围内的i(3,sqrt_n+1,2):
如果n%i==0:
返回(n,False)
返回(n,True)
def firstPrimes(n):
initTime=time.perf_计数器()
全球普利斯特
i=0
而len(pList)

任何帮助都将不胜感激

这可能是因为同步/进程启动开销。换句话说,启动另一个进程需要时间,在这种情况下,时间大于所获得的时间。@PiRocks我在Windows中检查了任务管理器,进程在那里,但只有1个在做某些事情。这与我所说的一致。如果大部分时间都花在与其他线程通信上,这可能表现为没有cpu时间花在工作线程上。根据python对这些术语的定义,您编写的代码是多进程的,而不是多线程的。我在使用带有大型稀疏矩阵的scipy.linalg.eigsh时观察到了完全相同的行为,代码的单线程执行速度大约是多线程执行速度的3倍。这可能是因为同步/进程启动开销。换句话说,启动另一个进程需要时间,在这种情况下,时间大于所获得的时间。@PiRocks我在Windows中检查了任务管理器,进程在那里,但只有1个在做某些事情。这与我所说的一致。如果大部分时间都花在与其他线程通信上,这可能表现为没有cpu时间花在工作线程上。根据python对这些术语的定义,您编写的代码是多进程的,而不是多线程的。我在使用带有大型稀疏矩阵的scipy.linalg.eigsh时观察到了完全相同的行为,代码的单线程执行速度大约是多线程执行速度的3倍。