How do I properly check the speed of my functions?

KilianS (3590 points)
5 9 27
asked Oct 30, 2021 in HW2 by KilianS (3,590 points)
I tried to take the time module and then take different ways to write a function and print out the time after in order to check the speed of the two functions. , but it always only gives me veeeery small differences.

Is there a better way to time it? or does that just mean that the functions actually all do run at kind of the same time
131 views

3 Answers

Best answer
gianluca5539 (9820 points)
3 6 44
answered Oct 31, 2021 by gianluca5539 (9,820 points)
selected Oct 31, 2021 by KilianS

Using a line profiler can be very helpful, just add @Profile on the line above your function declaration and run the profiler with kernprof, it will check line by line the time it took for that line to execute and also give you a percentage of the total function execution time. You obviously have to call that function in your "if name == main" so that it will execute. I recommend using very big datasets taken from the tests so you have better accuracy.

Check this line profiler, you will find all the information you need on this page.

Have a nice day!

KilianS (3590 points)
5 9 27
commented Oct 31, 2021 by KilianS (3,590 points)
nice day to you too, thanks!
andrea.sterbini (172680 points)
511 927 1776
commented Oct 31, 2021 by andrea.sterbini (172,680 points)
And if you have Spyder 4 you can run the line profiler from within with the spyder-line-profiler plugin
Luigi Pizza (6120 points)
11 20 65
answered Oct 30, 2021 by Luigi Pizza (6,120 points)
edited Oct 30, 2021 by Luigi Pizza

import time

t0 = time.time()
code_block
t1 = time.time()

total = t1-t0

This does not get the average of several trials

Or you can use TimeIt

For more info click here

KilianS (3590 points)
5 9 27
commented Oct 31, 2021 by KilianS (3,590 points)
correct me if im wrong but i thought timeit only times like short code snippets? I wanna time the pace of the entire function that compares two strings, or the one that takes out the spaces...
Luigi Pizza (6120 points)
11 20 65
commented Oct 31, 2021 by Luigi Pizza (6,120 points)
Yes, you're right
KilianS (3590 points)
5 9 27
commented Oct 31, 2021 by KilianS (3,590 points)
ok thanks for the first idea tho
GabrielAlexandru (7760 points)
2 4 29
answered Oct 30, 2021 by GabrielAlexandru (7,760 points)

If you installed the pytest-profiling library, then you can add --profile to the pytest command to see the time taken by the slowest functions. 

You can also use the spyder-line-profiler plugging for Spyder 4.

KilianS (3590 points)
5 9 27
commented Oct 31, 2021 by KilianS (3,590 points)
thanks i will try that