Set Speed Test
In order to see how fast functions take to run, you can use the
%timeit method that is built into IPython, which is an interactive Python terminal. So use
%timeit and then just put some expression like this. It will run it a bunch of times, find the mean, and then also find the standard deviation on how long it took.
01:49 And it took 71 microseconds plus or minus 480. So, let’s do Up arrow—oh, it actually remembered. So, it takes about the same amount of time to initialize a set with a 1,000 numbers, as it does a list.
02:25 Exit, clear, load. This is defined twice. So, basically, I’m using VS Code, which has a package called Python, which will show you if you have any syntax errors and also auto-format when you save. It’s just useful to make your coding a little bit faster.
02:54 So, we see here that initializing tuples takes longer than initializing sets and lists. Well, it’s mostly because here we are mutating our variables, while here we have to create a new tuple and then reassign it to here and add tuples together.
03:15 That’s a lot harder than just adding to an object that already exists in memory. But that wasn’t the point of this video, just something cool you learn when you start running functions and looking at how fast they take. What we really care about is membership.
This will happen outside the function, so this will happen when I load the file so it won’t actually be counted when I start timing these methods. Let’s just do
i in s. This is sort of an interesting expression here.
This is literally just like writing like
False or, like,
x * 10 or something. Like, it doesn’t actually do anything, because we’re not assigning it to anything, but it does execute the code.
05:07 This took 5.7 milliseconds plus or minus 25 microseconds, and it only did 100 loops. I’m assuming that this optimizes, because if it were to do 10,000 loops for everything, this would take way too long.
05:36 And here we’ll try the tuple. So, the tuple—checking membership in lists and tuples is pretty similar. Checking membership in sets is almost instant, or at least instant relative to lists and tuples, and is much faster.
Become a Member to join the conversation.