Benchmarking Code

Benchmarking your code is an important step to sustaining good code. It doesn’t significantly matter whether or not the language is “quick” or “sluggish” as every language has its goal platform the place it must do properly.

JavaScript Benchmarking Code

In JavaScript there’s a actually easy solution to measure the efficiency of your code and might be rally helpful to check simply on the shopper facet of your web browser.

Let us take a look at an instance:

operate reallyExpensiveFunction() {
  for (let i = 0; i < 10000; ++i) {

Enter fullscreen mode

Exit fullscreen mode

We will bench our capabilities by utilizing the operate console.time to start out and console.timeEnd to finish our bench.

Right here is an output you would possibly get

You’ll be able to do this instance on repl-it.

C Benchmarking Code

Imagine it or not, the identical code in C is similar to the JavaScript instance.

Let us take a look at this instance:

#embrace <stdio.h>
#embrace <time.h>

void really_expensive_function() {
  for (int i = 0; i < 10000; ++i) {

int most important() {
  clock_t begin = clock();
  clock_t finish   = clock();
  printf("Took %f secondsn", (((float)(finish-begin) / CLOCKS_PER_SEC)));
  return 0;

Enter fullscreen mode

Exit fullscreen mode

clock_t is a typedef for lengthy on my machine and is probably going the identical for yours. Regardless of that, you need to nonetheless use clock_t as it might be totally different on totally different machines. We get the system time earlier than and after the actually costly operate and are capable of get the period of time in seconds.

You’ll be able to do this instance on repl-it.

Right here is an output you would possibly get

C Output

Benchmarking Software program for Use




Ultimately it is as much as you the way you select to benchmark your code. Usually, you need to code your challenge earlier than you benchmark it and if efficiency is known as a concern then you may choose to make use of these benchmarking libraries or use a efficiency profile to search out bottlenecks. I hope you realized one thing right this moment :).

Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.

Checkout extra Articles on Sayed.CYou

#Benchmarking #Code