如果我将常用的调用代码放入单独的方法或文件中,Python 会更快吗?

发布于 2024-09-30 20:13:54 字数 126 浏览 1 评论 0原文

我想我曾经读过,如果将常用的代码放入方法或单独的文件中,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雨的味道风的声音 2024-10-07 20:13:54

没关系。不要围绕代码速度构建程序;围绕编码器速度构建它。如果你用 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.

杯别 2024-10-07 20:13:54

不。无论您将代码放在哪里,都必须解析一次并在必要时进行编译。将代码放入方法或不同文件中的区别可能会产生微不足道的性能差异,但您不必担心这一点。

目前唯一需要担心“正确”构造的语言是 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.

杀手六號 2024-10-07 20:13:54

有两件事:

单独模块中的代码在第一次运行时编译为字节码并保存为预编译的 .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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文