I’ve been wondering lately, when it comes to finding nodes in a scene, nodes which may or may no exist, which will be faster?
using a Try, Except?
or using maya’s built in objExists command?
My theory was that the Try, Except would be faster as objExists would have to loop over all nodes in the scene. At least as far as I assume.
So i put it to the test.
The first thing I neede ws a profiler. A little googling and I turned up Pyhtons Timeit module.
This can be imported using
import timeit print timeit.timeit(function)
This will print the result of running the specified function one milling times. Its is run this many times to ensure consistency in the results.
That can be reduced by adding the number flag, to specify how many times the code is run, so:
import timeit print timeit.timeit(function, number = 10000)
This will run the code ten thousand times. Its quicker and consistant enough for my requirements.
Getting into the problem at hand, I setup two functions, one as a Try, Except and another as objExists.
I ran each one in an empty scene and each one in a scene which included a complex character rig.
The code and results are below:
import maya.cmds as cmds import timeit def exists(): found = cmds.objExists('locator1') return found def select(): found = False try: cmds.select('locator1') found = True except: found = False return found print timeit.timeit(select, number = 10000)
The Try, Except took:
0.398722180715 in an empty scene and
0.376243066404 in a complex rig scene
where as the objExists took
0.0698589508479 in an empty scene and
0.0415636909748 in a complex rig scene
astonishing, and, contrary to my expectations, the Try, Except took nearly ten fold longer than the objExists!
From this I learned: Using specific commands looks to be faster than using Try, Except! I’ll have to test more commands and find out :)
If you’d like to try this code yourself, you can see the result for each funstion by changing this line:
print timeit.timeit(select, number = 10000)
print timeit.timeit(exists, number = 10000)