Let me write here the 3 most basic way to "properly time Sage computations". I think before looking at more intricate way to time code (e.g. asking to modify the code itself), one must first start with the basic ones or at least know they exists so that easy methods are used when they are sufficient.
Timing one call to a function with %time
:
sage: %time factor(2^300-1)
CPU times: user 5.42 ms, sys: 162 µs, total: 5.58 ms
Wall time: 7.31 ms
3^2 * 5^3 * 7 * 11 * 13 * 31 * 41 * 61 * 101 * 151 * 251 * 331 * 601 * 1201 * 1321 * 1801 * 4051 * 8101 * 63901 * 100801 * 268501 * 10567201 * 13334701 * 1182468601 * 1133836730401
Doing lots of call to a function and returns the best of 3 with %timeit
:
sage: %timeit factor(2^300-1)
100 loops, best of 3: 5.72 ms per loop
Profiling python code with %prun
:
sage: %prun factor(2^300-1)
8 function calls in 0.007 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.007 0.007 0.007 0.007 {method 'factor' of 'sage.rings.integer.Integer' objects}
1 0.000 0.000 0.007 0.007 <string>:1(<module>)
1 0.000 0.000 0.007 0.007 misc.py:2139(factor)
1 0.000 0.000 0.000 0.000 factorization_integer.py:30(__init__)
2 0.000 0.000 0.000 0.000 {isinstance}
1 0.000 0.000 0.000 0.000 proof.py:169(get_flag)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Most of the time, I am able to reduce my timing problem to using one of these three.
I'm not sure if I understand what you want but you could try defining a function which runs your code block and then use
timeit
on that.@j.c. What I want to achieve it something like this (I do not want to pass functions to
timeit
, instead I want to define start and end of a block that I want to time):That's certainly possible, see e.g. the examples using the standard python module
time
on this page https://zapier.com/engineering/profil... but that may not be as accurate as usingtimeit
since various background processes could affect the result.A good idea is to use a profiler. profile This will measure "all time consuming places" in the given code.
An other (not so good, but very often effective and cheap) idea is to print the second when the code passes through some points, then to manually look for the corresponding lines. E.g:
@j.c.@dan_fulea Thanks for the tips.