


Warum ist Python-Code schneller, wenn er innerhalb einer Funktion ausgeführt wird?
Why Does Python Code Execute More Swiftly in Functions?
Consider the Python code snippet below, which executes a loop 100 million times.
def main(): for i in range(10**8): pass main()
When measured in Linux using the time function, this code runs remarkably swiftly:
real 0m1.841s user 0m1.828s sys 0m0.012s
Curiously, if the for loop is executed without being enclosed within a function:
for i in range(10**8): pass
Its execution time increases considerably:
real 0m4.543s user 0m4.524s sys 0m0.012s
Why does this discrepancy occur?
Inside a Function
Examining the bytecode reveals the following when the code is within a function:
2 0 SETUP_LOOP 20 (to 23) 3 LOAD_GLOBAL 0 (xrange) 6 LOAD_CONST 3 (100000000) 9 CALL_FUNCTION 1 12 GET_ITER >> 13 FOR_ITER 6 (to 22) 16 STORE_FAST 0 (i) 3 19 JUMP_ABSOLUTE 13 >> 22 POP_BLOCK >> 23 LOAD_CONST 0 (None) 26 RETURN_VALUE
Outside a Function
In contrast, when the code is executed at the top level, the bytecode is as follows:
1 0 SETUP_LOOP 20 (to 23) 3 LOAD_NAME 0 (xrange) 6 LOAD_CONST 3 (100000000) 9 CALL_FUNCTION 1 12 GET_ITER >> 13 FOR_ITER 6 (to 22) 16 STORE_NAME 1 (i) 2 19 JUMP_ABSOLUTE 13 >> 22 POP_BLOCK >> 23 LOAD_CONST 2 (None) 26 RETURN_VALUE
The Crux of the Issue
The distinction lies in the use of STORE_FAST versus STORE_NAME. STORE_FAST is employed when the variable (in this case, i) is a local variable (within a function), whereas STORE_NAME is utilized when the variable is a global variable (outside a function). The former is significantly more efficient.
This can be explained by the fact that when a variable is declared as local, the interpreter can optimize the code to use a specific memory location for that variable. However, when a variable is declared as global, the interpreter must search through the entire global scope to find the variable, which is a more time-consuming process.
Das obige ist der detaillierte Inhalt vonWarum ist Python-Code schneller, wenn er innerhalb einer Funktion ausgeführt wird?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

SlicingPapythonListisDoneUsingthesyntaxlist [Start: Stop: Stufe] .here'Showitworks: 1) StartIndexoFtheFirstelementtoinclude.2) stopiStheIndexoFtheFirstelementtoexclude.3) StepisTheincrementBetweenelesfulFulForForforexcractioningPorporionsporporionsPorporionsporporesporsporsporsporsporsporsporsporsporionsporsPorsPorsPorsPorsporsporsporsporsporsporsAntionsporsporesporesporesporsPorsPorsporsPorsPorsporsporspors,

Numpyallowsforvariousoperationssonarrays: 1) BasicarithmeticliKeaddition, Subtraktion, Multiplikation und Division; 2) AdvancedoperationssuchasmatrixMultiplication;

Arraysinpython, insbesondere ThroughNumpyandpandas, areessentialfordataanalyse, öfterspeedandeffizienz.1) numpyarraysenableAnalysHandlingoflargedatasets und CompompexoperationslikemovingAverages.2) Pandasextendsnumpy'ScapaBilitiesWithDaTataforsForstruc

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

TensurepythonscriptsBehavectelyAcrossdevelopment, Staging und Produktion, UsethesStrategien: 1) Umweltvariablenforsimplesettings, 2) configurationFilesForComplexSetups und 3) dynamikloadingForAdaptability.eachMethodofferiqueNefits und Requiresca

Die grundlegende Syntax für die Python -Liste ist die Liste [START: STOP: STEP]. 1.Start ist der erste Elementindex, 2.Stop ist der erste Elementindex, und 3.Step bestimmt die Schrittgröße zwischen den Elementen. Scheiben werden nicht nur zum Extrahieren von Daten verwendet, sondern auch zum Ändern und Umkehrlisten.

ListSoutPer -CharakterArraysin: 1) Dynamics und Dynamics und 3), 2) StoringHeterogenData und 3) MemoryefficiencyForSparsedata, ButmayHavesLightPerformanceCostIncustonTectorationOperationen.

Toconvertapythonarraytoalist, Usethelist () constructororageneratorexpression.1) ImportThearrayModuleandCreateanarray.2) Uselist (arr) oder [xForxinarr] Toconvertittoalist in Betracht, überlegt Performance undMoryefficiencyForlargedatasets.


Heiße KI -Werkzeuge

Undresser.AI Undress
KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover
Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool
Ausziehbilder kostenlos

Clothoff.io
KI-Kleiderentferner

Video Face Swap
Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heißer Artikel

Heiße Werkzeuge

MantisBT
Mantis ist ein einfach zu implementierendes webbasiertes Tool zur Fehlerverfolgung, das die Fehlerverfolgung von Produkten unterstützen soll. Es erfordert PHP, MySQL und einen Webserver. Schauen Sie sich unsere Demo- und Hosting-Services an.

SAP NetWeaver Server-Adapter für Eclipse
Integrieren Sie Eclipse mit dem SAP NetWeaver-Anwendungsserver.

SublimeText3 chinesische Version
Chinesische Version, sehr einfach zu bedienen

MinGW – Minimalistisches GNU für Windows
Dieses Projekt wird derzeit auf osdn.net/projects/mingw migriert. Sie können uns dort weiterhin folgen. MinGW: Eine native Windows-Portierung der GNU Compiler Collection (GCC), frei verteilbare Importbibliotheken und Header-Dateien zum Erstellen nativer Windows-Anwendungen, einschließlich Erweiterungen der MSVC-Laufzeit zur Unterstützung der C99-Funktionalität. Die gesamte MinGW-Software kann auf 64-Bit-Windows-Plattformen ausgeführt werden.

Sicherer Prüfungsbrowser
Safe Exam Browser ist eine sichere Browserumgebung für die sichere Teilnahme an Online-Prüfungen. Diese Software verwandelt jeden Computer in einen sicheren Arbeitsplatz. Es kontrolliert den Zugriff auf alle Dienstprogramme und verhindert, dass Schüler nicht autorisierte Ressourcen nutzen.
