Is it possible to fasten the import of cgi?

Gabriel Genellina gagsl-py at
Thu Jan 18 18:15:44 CET 2007

"Cecil Westerhof" <dummy at> escribió en el mensaje 
news:45af8f52$0$339$e4fe514c at
> Gabriel Genellina wrote:
>> "Cecil Westerhof" <dummy at> escribió en el mensaje
>> news:45af6f47$0$322$e4fe514c at
>>>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse
>>> can not time the time used to import time, but os and sys do not take
>>> more as a millisecond. My script itself takes 3 or 4 milliseconds. But
>>> importing
>>> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
>>> there a way to make this more fast? The import off cgi makes the script
>>> at least 20 times as slow. Something like mod-python is not a
>>> possibility. I could use it on my test machine, but not at the osting
>>> provider.
>> Surely os was imported earlier, and was already loaded. sys is a builtin
>> module. But I think your problem is not how much time takes importing 
>> cgi,
>> but how much time takes launching a new python process on each request.
> Nope, it was certainly cgi. When I fetch time after importing and after 
> the
> script finishes, the difference is 4 milliseconds. If I import the modules
> apart from cgi after I fetch the first time, there is added about 1
> millisecond to the difference. When I also import cgi after taking the
> time, the difference grows with 95 milliseconds. So for one reason ore
> another, cgi is very expensive.

I'll try to explain better: the cgi *protocol* (I'm not talking about the 
cgi *module*) requires a *new* python process to be created on *each* 
request. Try to measure the time it takes to launch Python, that is, the 
time from when you type `python ENTER` on your shell and the interpreter 
prompt appears. That time is wasted for *every* cgi request, and I bet it is 
much greater than the 95 ms you measure importing a module (be it cgi or 
whatever). You'll gain much more responsiveness if you can switch to another 
protocol, be it FastCGI, WSGI, mod_python or another.

Anyway, comparing the import time between os, sys, and cgi is not very 
meaningful. sys is a builtin module, so "import sys" does very little. os is 
likely to be already imported by the time your script begins, so "import os" 
just verifies that os is already in sys.modules. "import cgi" is the only 
example when Python actually has to load something, so it's not a surprise 
if it takes longer.

Gabriel Genellina 

More information about the Python-list mailing list