Fast Vector scale
-
Anyone got any good tips for a fast Geom::Vector3d scale? Along with a few others, its a function thats sorely missing in the API. Initially, I trivially did:
def scale(s) Geom::Vector3d.new(self.x * s,self.y * s, self.z * s) end
However, this is waaay slower than the Vector3d#length function which (must) do slightly more work. I'm currently using (brace yourself for the horror):
vec = (vtmp = aVector; vtmp.length = vtmp.length * aNewLength; vtmp)
where aVector and aNewLength are effective parameters.
Its actually faster..but just so ugly.
-
why this testcase doesnt work ? I am missing something ?
later edit: duh, vtmp = v.clone otherwise it will change the original vector
from my tests scale2 is like 26-30% speed increasedef scale(v,s) Geom;;Vector3d.new(v.x * s,v.y * s, v.z * s) end def scale2(v,s) vtmp = v; vtmp.length = vtmp.length * s vtmp end v1 = Geom;;Vector3d.new(5,1,5) n1 = 10 t1 = Time.now begin 50000.times do |x| scale2(v1,n1) end rescue => err p err end p Time.now - t1
-
yes, that my point - that the internal function (length) that does something like *Math.sqrt(v.dot(v))*is faster than 3 scalar multiplies.. A bit sad.
Adam
-
because the internal function length is done in C world and those 3 scalar multiplies in Ruby world (which of course is slower)
Advertisement