Opened 4 years ago

Last modified 4 years ago

## #22412 new defect

# timeit("...") does not work inside a function

Reported by: | nthiery | Owned by: | |
---|---|---|---|

Priority: | major | Milestone: | sage-7.6 |

Component: | misc | Keywords: | |

Cc: | Merged in: | ||

Authors: | Reviewers: | ||

Report Upstream: | N/A | Work issues: | |

Branch: | Commit: | ||

Dependencies: | Stopgaps: |

### Description

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).

Let's take an example, where we time a non trivial factorization:

sage: p = (1-x^100) sage: timeit('factor(p)', seconds=True) 0.007231048583984375

Now, let's do the same inside a function:

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

I am not sure there is an easy fix, but at least this limitation needs to be documented.

**Note:**See TracTickets for help on using tickets.

Note that the following seems to work:

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).