Sage: Ticket #22412: timeit("...") does not work inside a function
https://trac.sagemath.org/ticket/22412
<p>
Apparently, timeit('some expression') evaluates the expression in the
context of the interpreter rather than the local context where timeit
is being called, which can lead to unexpected results (some students
of mine got trapped today).
</p>
<p>
Let's take an example, where we time a non trivial factorization:
</p>
<pre class="wiki"> sage: p = (1-x^100)
sage: timeit('factor(p)', seconds=True)
0.007231048583984375
</pre><p>
Now, let's do the same inside a function:
</p>
<pre class="wiki"> sage: def f(p):
....: return timeit('factor(p)', seconds=True)
sage: f(p) # That's normal
0.007200319290161133
sage: f(1) # OOPS, That should be instantaneous!
0.007200319290161133
</pre><p>
I am not sure there is an easy fix, but at least this limitation needs
to be documented.
</p>
en-usSagehttps://trac.sagemath.org/chrome/site/logo_sagemath_trac.png
https://trac.sagemath.org/ticket/22412
Trac 1.1.6tmonteilSun, 26 Feb 2017 13:22:54 GMT
https://trac.sagemath.org/ticket/22412#comment:1
https://trac.sagemath.org/ticket/22412#comment:1
<p>
Note that the following seems to work:
</p>
<pre class="wiki">sage: def f(p):
....: return timeit('factor({})'.format(p), seconds=True)
sage: p = (1-x^100)
sage: f(p)
0.013366518020629882
sage: f(1)
4.191055297851562e-05
</pre><p>
I am not sure whether what you reported should be considered as a bug however (there is some local/global context issue but i am not sure about how Python should behave in such a case).
</p>
Ticket