简体   繁体   English

python import语句的位置会影响性能吗

[英]Does the position of python import statements affect performance

I was wondering if the position of import statements in a python program has any affect on performance. 我想知道python程序中import语句的位置是否对性能有影响。 For example if I have this 例如,如果我有这个

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib2
import json
import requests
from flask import render_template, request, Flask, session, Markup, jsonify, send_from_directory
from wit import Wit
from os import urandom
from datetime import datetime
from uuid import uuid1
from random import choice
from FAAWrapper import FAA_API
from bs4 import BeautifulSoup



def function1():
    from OpenSSL import SSL
    from fuzzywuzzy import process
    continue

def function2():
    continue

Would performance be adversely affected by calling function1() being that function1 contains import statements? 如果function1包含import语句,调用function1()会对性能产生不利影响吗? Should all of my imports be placed at the top or does the import only happen once the first time the function is called? 应该将我所有的导入放置在顶部,还是仅在第一次调用该函数时才进行导入?

Importing does two things: 导入有件事:

  1. If there is no sys.modules entry yet, find and load the module; 如果还没有sys.modules条目,请查找并加载该模块; if Python code, executing the top-level code produces the namespace for that module. 如果是Python代码,则执行顶级代码将为该模块生成名称空间。 This step is skipped if the module has already been loaded. 如果模块已经加载,则跳过此步骤。

  2. Bind a name in the current namespace to the imported object. 将当前名称空间中的名称绑定到导入的对象。 import foo sets the name foo . import foo设置名称foo from foo import bar binds the name bar , etc. from foo import bar绑定名称bar等。

Now, local names (in functions) have a speed advantage in that Python stores these in a C array and uses indices in the bytecode to reference them. 现在, 本地名称(在函数中)具有速度优势,因为Python将它们存储在C数组中,并使用字节码中的索引来引用它们。 Global names are stored in a dictionary and have a small hashing overhead each time you do a lookup. 全局名称存储在字典中,并且每次进行查找时哈希开销很小。

So importing something into a function results in a local, accessing which is faster than referencing a global. 因此,将某些内容导入到函数中会导致局部访问比引用全局更快。 This is offset by the hash lookup in sys.modules each time your function runs so only if the name is used in a loop would you notice this. 每次运行函数时,都会通过sys.modules的哈希查找来抵消此偏移,因此只有在循环中使用该名称时,您才会注意到这一点。

However, you should only make such optimisations if that code is used on a critical path, in code that is executed a lot. 但是,仅应在经常执行的代码中的关键路径上使用该代码时,才应进行此类优化。 You are paying a maintenance price by hiding imports in functions, and that cost needs to be weighed against the (marginal) speed benefits. 您通过隐藏函数中的导入来支付维护成本,并且需要权衡成本(边际)的速度优势。

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

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