Python question - first call is slower?
Oleg Goldshmidt
pub at goldshmidt.org
Wed Jun 20 09:35:54 IDT 2012
On Wed, Jun 20, 2012 at 12:27 AM, Nadav Har'El <nyh at math.technion.ac.il>wrote:
> Hi, I have run across a puzzling issue in Python, and I wonder if anyone
> on the list can explain it.
>
> I have a python function which takes some input and produces some
> output - it doesn't keep permanent state, and presumably running it
> twice would do exactly the same thing twice, and take exactly the same
> time.
>
> But strangely, it doesn't - the first call takes 14 milliseconds, while
> the second and all subsequent calls take only 2 milliseconds each.
> Does anybody have any idea why this can happen?
>
Guessing wildly (I don't know much about Python's inner workings, thinking
system here): maybe some libraries get dynamically loaded into memory the
first time and reused later?
>
> I considered, and discredited, the following attempted "explanations":
>
> <...>
>
> 3. "If class A imports B which imports C which imports D, some of these
> classes are only read when the code is actually used for the first
> time". Again, I couldn't find any evidence that this is true in Python
> (unlike, e.g., Java). An "import" would read the whole class hierarchy
> into
> memory. Right?
>
I would - naively! - think that "stuff (not only, or necessarily, the
python code stuff, but also what it needs from the system) would indeed be
loaded dynamically when it is needed. I don't base this on anything I know,
but on the intuitive notion that whatever Python does works as "normal C
libraries" - it's implemented in C, right?
Another (kinda related) possibility - some cacheing going on?
What happens if you run the program twice - is the first call slow every
time or just the first time?
In general, t does not surprise me that something - whatever - runs slower
the first time than subsequent times - it happens often.
--
Oleg Goldshmidt | pub at goldshmidt.org <oleg at goldshmidt.org>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.cs.huji.ac.il/pipermail/linux-il/attachments/20120620/dd33b83b/attachment-0001.html>
More information about the Linux-il
mailing list