我正在使用以下代码生成Mandelbrot集分形,但无论我使用的线程数,计算时间都没有真正改变(大约5s)。我正在使用英特尔i5-4200M处理器,所以我应该得到至少4个线程不同的结果,但事实并非如此。我错过了什么?我想通过使用1个线程并将其与使用更多来比较来计算加速,但我得到的差异不会超过几毫秒。逃逸时间算法用于生成。
# Multi-threaded Mandelbrot Fractal (Do not run using IDLE!)
# FB - 201104306
import threading
import math
import time
import sys
from PIL import Image
START_TIME = 0
w = 1080 # image width
h = 1080 # image height
image = Image.new("RGB", (w, h))
wh = w * h
maxIt = 256 # max number of iterations allowed
# drawing region (xa < xb & ya < yb)
xa = -2.0
xb = 1.0
ya = -1.5
yb = 1.5
xd = xb - xa
yd = yb - ya
numThr = 1 # number of threads to run
# lock = threading.Lock()
class ManFrThread(threading.Thread):
def __init__ (self, k):
self.k = k
threading.Thread.__init__(self)
def run(self):
# each thread only calculates its own share of pixels
for i in range(k, wh, numThr):
kx = i % w
ky = int(i / w)
a = xa + xd * kx / (w - 1.0)
b = ya + yd * ky / (h - 1.0)
x = a
y = b
for kc in range(maxIt):
x0 = x * x - y * y + a #x0 = x * x - y * y + math.exp(-x) * (a * math.cos(y) + b * math.sin(y))
y = 2.0 * x * y + b #y = 2.0 * x * y + math.exp(-x) * (b * math.cos(y) - a * math.sin(y))
x = x0
if x * x + y * y > 4:
# various color palettes can be created here
red = (kc % 8) * 32
green = (16 - kc % 16) * 16
blue = (kc % 16) * 16
# lock.acquire()
global image
image.putpixel((kx, ky), (red, green, blue))
# lock.release()
break
if __name__ == "__main__":
START_TIME = time.time()
numThr = sys.argv[1]
try:
numThr = int(numThr)
except:
print("value must be int")
tArr = []
for k in range(numThr): # create all threads
tArr.append(ManFrThread(k))
for k in range(numThr): # start all threads
tArr[k].start()
for k in range(numThr): # wait until all threads finished
tArr[k].join()
image.save("MandelbrotFractal.png", "PNG")
print("-*-*- %s seconds -*-*-" % (time.time() - START_TIME))