r/tinycode • • Jan 09 '13

Ray tracer in 140 SLOC of python with picture

I have be playing with raytracing for a while now and wanted to write something that was simple to understand but produced a cool effect. There is defiantly many more features that could be added, like reflections and multiple light sources, but I wanted to stay as minimalistic possible.

Source: http://pastebin.com/F8f5GHJZ

Image: http://imgur.com/prPGk

70 Upvotes

35 comments sorted by

View all comments

Show parent comments

3

u/theinternetftw Jan 10 '13 edited Jan 10 '13

Surprisingly, not using a class for vectors improves runtime by 2x.

(which is why I used those more cumbersome functions in my raytracing code, but I'd forgotten just how dramatic the speedup was)

4

u/Twirrim Jan 10 '13

Is there a particular reason why functions are quicker than classes? Naively I assumed that mostly under the surface it would execute / optimize mostly the same?

thought I'd randomly chuck these through pypy 1.9, 26s->11s for the standard code python vs pypy, then 16s->11s for your function based code.

4

u/theinternetftw Jan 10 '13 edited Jan 10 '13

(complete speculation follows) I *think* it might have to do with the fact that vectors simply become lists in my code, and python can optimize lists with more confidence than classes (which can change at runtime). Just a guess.

That pypy handles both styles with ease is interesting. I don't know what that means either.

Edit: To get something other than speculation, I profiled the two versions a bit.

Initialization is pretty expensive: 7 out of 55 seconds for creating all the vector objects, with no equivalent time found in the classless version (12,225,276 vectors used in tracing that scene, btw). That's not enough to account for all the speedup though.

Near as I can tell other than that, it's just that doing operations on list elements is cheaper than accessing multiple class fields for every arithmetic operation you do (in which you often instantiate a new object to return a result). Wish I had a better answer though, as that's kinda just back to guessing.

I'm also interested in how pypy gets rid of the problem.

edit: a comment in a different post I linked in to suggests the main problem is just that objects are just dictionaries of attributes, so accessing those attributes introduces hashing to every simple operation.

3

u/Wavicle Jan 11 '13

Is there a particular reason why functions are quicker than classes?

Because when you do a method call you aren't directly doing a call to your function. Class instance methods are themselves instances of the instancemethod class which has the class for the function you actually wrote as an attribute called im_func. Perhaps this will make more sense:

>>> class foo:
	def do_something(self):
		print "Hello, World!"
>>> def bar():
	print "Hello, World!"
>>> f = foo()
>>> f.do_something.__class__
<type 'instancemethod'>
>>> f.do_something.im_func.__class__
<type 'function'>
>>> bar.__class__
<type 'function'>

When you do f.do_something you do not directly call the function you wrote. You invoke the instancemethod class which then does something akin to self.im_func(self.im_self, *args, **kwargs).

So the big speed difference here is because these functions do very little, thus the call overhead is a substantial fraction of their execution time. In the case of calling instance methods, the overhead is double.

Hopefully that made some sense.

2

u/Twirrim Jan 11 '13

Hopefully that made some sense

That made a lot of sense, thanks :)

2

u/Wavicle Jan 11 '13

I should probably have included that what theinternetftw said about Vector object creation taking up some of the time is valid as well. normal, __add__, __sub__ and __mul__ all create new Vector objects in the original code.

3

u/Wavicle Jan 11 '13

Since Python tuples are immutable, CPython can optimize access to them. I replaced what I think are all the Vector-as-lists with tuples and saw a little over 10% speedup in the single-threaded case: http://pastebin.com/yrH2vT7z

Of course if you want the ability to change individual vector components without creating a new object, you will have to revert to using lists.

1

u/theinternetftw Jan 11 '13

Cool, that really makes sense. I'm not used to doing things with python where performance ends up really mattering, so all of this stuff is new to me (so glad to finally know it, though). In browsing around I've also found slots and namedtuples as ways to get the convenience of a class without the performance hit you get from accessing normal python objects.

1

u/Yeknom Jan 10 '13

So the maxRecur is not actually used in this implementation. It would be used if the trace function was made recursive. Making the trace function recursive would allow it to model translucent, and reflective surfaces. The maxRecur value would be decremented each time the function was called so the ray tracer could avoid tracing to infinity for example between two mirrors or inside something with total internal reflection.

TLDR: Not used