[Tutor] sharing a small script someone may find of use
Nathan Smith
nathan-tech at hotmail.com
Fri Aug 12 20:53:42 EDT 2022
I wanted to share this small script I wrote today with the list as I
thought 1, someone might find it useful, and 2, feedback! :)
Use case: This script can be used to identify which modules are holding
things up at the import stage and give you a rough estimate as to how
long your imports are taking for a program during start up.
Limitations: Doesn't like from . import x, although this can be resolved
easily with a minor edit.
Script:
import time
import importlib
slist=[]
file=input("What file should I read?")
modules=[]
f=open(file, "r")
data=f.readlines()
f.close()
for x in data: # get the list of modules and remove any end of line
characters
if(x.startswith ("import") or x.startswith("from")):
word=x.split(" ")
if(word[1] not in modules):
modules.append(word[1].strip("\n"))
print("Found "+str(len(modules))+" modules.")
for x in modules:
start=time.time()
r=importlib.import_module(x)
if(time.time()==start): # probably cached
importlib.reload(r)
slist.append([x, time.time()-start])
slist.sort(key=lambda x: x[1])
total=0
for x in slist:
print(x[0], ": ", x[1])
total=total+x[1]
print("Total: "+str(total))
I know I'm very paren happy, it's a habit from coding in a different
language that requires it :) But any other feedback welcome!
I hope someone finds this of use.
--
Best Wishes,
Nathan Smith, BSC
My Website: https://nathantech.net
More information about the Tutor
mailing list