gpt4 book ai didi

python - 用多线程计算 Pi(没有加速 - 做什么)

转载 作者:行者123 更新时间:2023-11-28 19:56:53 26 4
gpt4 key购买 nike

我正在尝试使用 Ramanujan 的公式之一在 Python 上以任意精度计算圆周率:http://en.wikipedia.org/wiki/Approximations_of_%CF%80#20th_century .它基本上需要大量的阶乘和高精度的 float 除法。

我正在使用多个线程来划分无限级数计算,方法是为每个线程提供除以线程数时具有特定模数的所有成员。所以如果你有3个线程,总和应该这样划分 线程 1 ---> 1, 4, 7... 成员 线程 2 ----> 2, 5, 8... 线程 3 ---->3、6、9...

到目前为止,这是我的代码:

from decimal   import *
from math import sqrt, ceil
from time import clock
from threading import *
import argparse

memoizedFactorials = []
memoizedFactorials.append( 1 )
memoizedFactorials.append( 1 )

class Accumulator:
def __init__( self ):
self._sum = Decimal( 0 )

def accumulate( self, decimal ):
self._sum += decimal

def sum( self ):
return self._sum

def factorial( k ):
if k < 2: return 1
elif len(memoizedFactorials) <= k:
product = memoizedFactorials[ - 1 ] #last element
for i in range ( len(memoizedFactorials), k+1 ):
product *= i;
memoizedFactorials.append(product)

return memoizedFactorials[ k ]

class Worker(Thread):
def __init__( self, startIndex, step, precision, accumulator ):
Thread.__init__( self, name = ("Thread - {0}".format( startIndex ) ) )
self._startIndex = startIndex
self._step = step
self._precision = precision
self._accumulator = accumulator

def run( self ):
sum = Decimal( 0 )
result = Decimal( 1 )
zero = Decimal( 0 )

delta = Decimal(1)/( Decimal(10)**self._precision + 1 )
#print "Delta - {0}".format( delta )
i = self._startIndex
while( result - zero > delta ):
numerator = Decimal(factorial(4 * i)*(1103 + 26390 * i))
denominator = Decimal((factorial(i)**4)*(396**(4*i)))
result = numerator / denominator
print "Thread - {2} --- Iteration - {0:3} --->{1:3}".format( i, result, self._startIndex )
sum += result
i += self._step

self._accumulator.accumulate( sum )
print

def main( args ):
numberOfDigits = args.numberOfDigits;
getcontext().prec = numberOfDigits + 8
zero = Decimal(1) / Decimal( 10**( numberOfDigits + 1 ) )

start = clock()
accumulator = Accumulator()

threadsCount = args.numberOfThreads;
threadPool = []
for i in range(0, threadsCount ):
worker = Worker( i, threadsCount, numberOfDigits, accumulator )
worker.start()
threadPool.append( worker )

for worker in threadPool:
worker.join()

sum = accumulator.sum();

rootOfTwo = Decimal(2).sqrt()

result = Decimal( 9801 ) / ( Decimal( 2 ) * rootOfTwo * sum )
end = clock();

delta = end - start;

print result;
print ("Took it {0} second to finish".format( delta ) )

#testing the results
#realPiFile = open("pi.txt");
#myPi = str(result)
#realPi = realPiFile.read( len(myPi) - 1 )

#if ( myPi[:-1] != realPi ):
# print "Answer not correct!"
# print "My pi - {0}".format(myPi)
# print "Real pi - {0}".format(realPi)

if __name__ == '__main__':
parser = argparse.ArgumentParser(description = 'Calculate Pi at with arbitrary precision')
parser.add_argument('-p', dest = 'numberOfDigits', default=20, type = int, help ='Number of digits in pi ')
parser.add_argument('-t', '--tasks', dest = 'numberOfThreads', default=1, type = int, help ='Number of tasks( threads )')
parser.add_argument('-o', dest = 'outputFileName', type = str, help ='Connect to VCS testing servers')
parser.add_argument('-q', '--quet', dest = 'quetMode' , action='store_true', help ='Run in quet mode')

args = parser.parse_args()

print args
main(args)
a = raw_input("Press any key to continue...")

让我担心的是,在使用多线程时我的时间加速非常小或没有。例如圆周率的 1000 位: 1 个线程 --> 0.68 秒 2 个线程 --> 0.74 秒 4 个线程 --> 0.75 秒 10 个线程 --> 0.96 秒

关于如何减少时间,您有什么想法吗?我在任务管理器上看到,当使用四个线程时,我的两个核心都参与了 100%。然而时间似乎是一样的。

PS:这是一项家庭作业,所以我不能使用其他公式。 PSS:我使用的是 python 2.7

谢谢:)

最佳答案

Python 有一个 GIL( Global Interpreter Lock ) 可以防止多个线程同时执行 python 代码,也就是说,您无法使用多个线程来加快 CPU 密集型任务的速度。您必须使用多个进程。

关于python - 用多线程计算 Pi(没有加速 - 做什么),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16926853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com