Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1
Назад: The Array: The Foundational Data Structure
Дальше: Reading

Measuring Speed

So how do we measure the speed of an operation?

If you take away just one thing from this book, let it be this: when we measure how “fast” an operation is, we do not refer to how fast the operation takes in terms of pure time, but instead in how many steps it takes.

We’ve actually seen this earlier in the context of printing the even numbers from 2 to 100. The second version of that function was faster because it took half as many steps as the first version did.

Why do we measure code’s speed in terms of steps?

We do this because we can never say definitively that any operation takes, say, five seconds. While a piece of code may take five seconds on a particular computer, that same piece of code may take longer on an older piece of hardware. For that matter, that same code might run much faster on the supercomputers of tomorrow. Measuring the speed of an operation in terms of time is undependable, since the time will always change depending on the hardware it’s run on.

However, we can measure the speed of an operation in terms of how many computational steps it takes. If Operation A takes 5 steps, and Operation B takes 500 steps, we can assume that Operation A will always be faster than Operation B on all pieces of hardware. Measuring the number of steps is, therefore, the key to analyzing the speed of an operation.

Measuring the speed of an operation is also known as measuring its time complexity. Throughout this book, I’ll use the terms speed, time complexity, efficiency, performance, and runtime interchangeably. They all refer to the number of steps a given operation takes.

Let’s jump into the four operations of an array and determine how many steps each one takes.

Назад: The Array: The Foundational Data Structure
Дальше: Reading