3 ms·
I think it's kinda interesting what tiny little tweaks will affect code speed- I recently discovered that in python, if you're only going to use an import for o
by Vexs 10y ago
I think it's kinda interesting what tiny little tweaks will affect code speed- I recently discovered that in python, if you're only going to use an import for one or two functions, importing it locally shaves off a good bit of time depending on the function, in my case, .2 seconds!
- Cyphase 10y agoI don't think the function itself matters; what's going on is that if you import it locally, the reference you're using is in the local namespace versus being in a module's namespace, which means it takes less time to get to the function object. I'm guessing the function is being called a fair number of times in a loop or some such similar manner?
- bbernoulli 10y agoI agree, seems likely. gp can use dis.dis() to confirm this...
- fnord123 10y agoYou could use `from some_module import some_func` to get the same effect as some_func will be in the local namespace.
- Cyphase 10y agoThat's what the top-level commenter was doing.
- fnord123 10y agoOk. It wasn't clear what "importing it locally" meant. I've worked with some people who would use that phrase to mean "copy paste it into the local file".
- Cyphase 10y agoFair point :P. I think I might have seen someone mean it like that as well in the past.
- masklinn 10y agoAnd a common stdlib trick is to bind these via function arguments e.g. def foo(a, b, thing=util.thing): ...
- fnord123 10y agoPython is notable for how it harasses the filesystem. If your python program is running off NFS or parallel filesystems (e.g. gpfs, panasas, lustre, etc) then you may get a lot more performance from avoiding imports. Especially if pkg_resource is being used.