简体   繁体   English

导入 Python 模块会影响性能吗?

[英]Does importing a Python module affect performance?

When searching for a solution, it's common to come across several methods.在寻找解决方案时,通常会遇到几种方法。 I often use the solution that most closely aligns with syntax I'm familiar with.我经常使用与我熟悉的语法最接近的解决方案。 But sometimes the far-and-away most upvoted solution involves importing a module new to me, as in this thread .但有时最受好评的解决方案涉及导入一个对我来说是新的模块,就像在这个线程中一样

I'm already importing various modules in large script that will be looping 50K times.我已经在将循环 50K 次的大型脚本中导入各种模块。 Does importing additional modules affect processing time, or otherwise affect the script's efficiency?导入附加模块是否会影响处理时间,或者是否会影响脚本的效率? Do I need to worry about the size of the module being called?我需要担心被调用模块的大小吗? Seeking guidance on whether, generally, it's worth the extra time/effort to find solutions using methods contained in modules I'm already using.寻求有关使用我已经在使用的模块中包含的方法来寻找解决方案的额外时间/努力是否值得的指导。

Every bytecode in Python affects performance. Python 中的每个字节码都会影响性能。 However, unless that code is on a critical path and repeated a high number of times, the effect is so small as to not matter.但是,除非该代码位于关键路径上并且重复了很多次,否则影响小到无关紧要。

Using import consists of two distinct steps: loading the module (done just once ), and binding names (where the imported name is added to your namespace to refer to something loaded by the module, or the module object itself).使用import包含两个不同的步骤:加载模块(只完成一次)和绑定名称(将导入的名称添加到命名空间以引用模块加载的内容或模块对象本身)。 Binding names is almost costless.绑定名称几乎是免费的。 Because loading a module happens just once, it won't affect your performance.因为加载一个模块只发生一次,它不会影响你的性能。

Focus instead on what the module functionality can do to help you solve your problem efficiently.而是专注于模块功能可以做什么来帮助您有效地解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM