Sometimes you'd like to measure how two implementations compare in regards to run time. In this lesson you will learn how to quickly do this using Console.time and constole.timeEnd.
Instructor: [0:01] We have two functions here, runFaster() and runSlower(). We'd like to benchmark them and see if runFaster is really faster than runSlower.
[0:13] One way to do this is by using console.time(). I create a function called testFunctionRuntime(). It accepts repeats, how many times to repeat the function under test. It also accepts the function and log text.
[0:30] I'm going to add two console calls, console.time() and console.timeEnd(). Chrome will calculate the time that passed between time and timeEnd with the same log text and log into the console.
[0:44] Our function under test will run between these two console commands. I wrap the function with a for-loop, so it will repeat repeats time. Let's test this in the browser.
[0:55] In the console I run testFunctionRuntime, and pass it 100 repeats, runFaster and the log text "run faster". Running the function, we see it logged our text with the time it took the function to run 100 times. I do the same for runSlower. It shows us that runSlower indeed runs slower.
[1:17] To recap, you can measure the time it takes a piece of code to run by wrapping it with console.time() and console.timeEnd() with the same text. It is usually better to benchmark multiple repeats of the function in order to reduce the effect of one or two off-runs. This is why we used the repeats in the benchmark.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!