我在python中有一个简单的光线跟踪器.渲染图像200x200需要4分钟,这对我来说绝对太过分了.我想改善这种情况.
一些要点:我为每个像素拍摄多条光线(以提供抗锯齿),每个像素总共有16条光线.200x200x16总计640000条光线.必须测试每条光线对场景中多个Sphere对象的影响.雷也是一个相当微不足道的对象
class Ray(object):
def __init__(self, origin, direction):
self.origin = numpy.array(origin)
self.direction = numpy.array(direction)
Run Code Online (Sandbox Code Playgroud)
Sphere稍微复杂一些,并且带有hit/nohit的逻辑:
class Sphere(object):
def __init__(self, center, radius, color):
self.center = numpy.array(center)
self.radius = numpy.array(radius)
self.color = color
@profile
def hit(self, ray):
temp = ray.origin - self.center
a = numpy.dot(ray.direction, ray.direction)
b = 2.0 * numpy.dot(temp, ray.direction)
c = numpy.dot(temp, temp) - self.radius * self.radius
disc = b * b - 4.0 * a * c
if (disc < 0.0):
return None
else:
e = math.sqrt(disc)
denom …Run Code Online (Sandbox Code Playgroud) 根据我所知道的numpy,一次将一个操作应用于一个数组的每一行是个坏主意.广播显然是首选方法.鉴于此,我如何获取具有形状的数据(N,3)并将其转换为质心?以下是我正在使用的"坏方法".这有效,但我怀疑它会有大的性能影响N:
CM = R.sum(0)/R.shape[0]
for i in xrange(R.shape[0]): R[i,:] -= CM
Run Code Online (Sandbox Code Playgroud) 检查我的以下代码; 它是在python中实现的sigma_2函数(使用原始筛选)的一部分,它是除数函数之一http://mathworld.wolfram.com/DivisorFunction.html
from time import time
from itertools import count
import numpy
def sig2(N, nump=False):
init = time()
#initialize array with value=1 since every positive integer is divisible by 1
if nump:
print 'using numpy'
nums = numpy.ones((N,), dtype=numpy.int64)
else:
nums = [1 for i in xrange(1, N)]
#for each number n < N, add n*n to n's multiples
for n in xrange(2, N):
nn = n*n
for i in count(1):
if n*i >= N: break
nums[n*i-1] += nn …Run Code Online (Sandbox Code Playgroud)