如果我将常用的调用代码放入单独的方法或文件中,Python 会更快吗?
我想我曾经读过,如果将常用的代码放入方法或单独的文件中,Python 的编译和运行速度会稍微快一些。将 Python 代码放入方法中是否比单独的文件更有优势,反之亦然?有人可以解释这是为什么吗?我认为它与内存分配和垃圾收集或其他东西有关。
I thought I once read on SO that Python will compile and run slightly more quickly if commonly called code is placed into methods or separate files. Does putting Python code in methods have an advantage over separate files or vice versa? Could someone explain why this is? I'd assume it has to do with memory allocation and garbage collection or something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没关系。不要围绕代码速度构建程序;围绕编码器速度构建它。如果你用 Python 写东西并且速度太慢,可以使用 cProfile 找到瓶颈并加快速度。你如何加快速度?你尝试一些事情并分析它们。一般来说,关键循环中的函数调用开销很高。字节编译代码只需要很少的时间,并且只需要完成一次。
It doesn't matter. Don't structure your program around code speed; structure it around coder speed. If you write something in Python and it's too slow, find the bottleneck with cProfile and speed it up. How do you speed it up? You try things and profile them. In general, function call overhead in critical loops is high. Byte compiling your code takes a very small amount of time and only needs to be done once.
不。无论您将代码放在哪里,都必须解析一次并在必要时进行编译。将代码放入方法或不同文件中的区别可能会产生微不足道的性能差异,但您不必担心这一点。
目前唯一需要担心“正确”构造的语言是 Javascript。因为它必须从网络下载到客户的计算机上。这就是为什么有如此多的压缩器和混淆器。像这样的事情不会用 Python 完成,因为不需要它。
No. Regardless of where you put your code, it has to be parsed once and compiled if necessary. Distinction between putting code in methods or different files might have an insignificant performance difference, but you shouldn't worry about it.
About the only language right now that you have to worry about structuring "right" is Javascript. Because it has to be downloaded from net to client's computer. That's why there are so many compressors and obfuscators for it. Stuff like this isn't done with Python because it's not needed.
有两件事:
单独模块中的代码在第一次运行时编译为字节码并保存为预编译的 .pyc 文件,因此只要源代码没有在下次运行时就不必重新编译它此后没有被修改。这可能会带来一点性能优势,但仅限于程序启动时。
此外,如果将变量等放置在函数内部而不是文件的顶层,Python 存储变量等的效率会更高一些。但我不认为这就是你在这里指的,是吗?
Two things:
Code in separate modules is compiled into bytecode at first runtime and saved as a precompiled
.pyc
file, so it doesn't have to be recompiled at the next run as long as the source hasn't been modified since. This might result in a small performance advantage, but only at program startup.Also, Python stores variables etc. a bit more efficiently if they are placed inside functions instead of at the top level of a file. But I don't think that's what you're referring to here, is it?