Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 19, 2021 11:33 pm GMT

Benchmarking Code

Benchmarking your code is a very important step to maintaining good code. It does not particularly matter whether the language is "fast" or "slow" as each language has its target platform where it needs to do well.

JavaScript Benchmarking Code

In JavaScript there is a really simple way to measure the performance of your code and can be rally useful to test easily on the client side of your web browser.

Let's look at an example:

function reallyExpensiveFunction() {  for (let i = 0; i < 10000; ++i) {    console.log("Hi
"); }}console.time('reallyExpensiveFunction');console.timeEnd('reallyExpensiveFunction');

We can bench our functions by using the function console.time to start and console.timeEnd to end our bench.

Here is an output you might get

JS Output

You can try this example on repl-it.

C Benchmarking Code

Believe it or not, the same code in C is very similar to the JavaScript example.

Let's look at this example:

#include <stdio.h>#include <time.h>void really_expensive_function() {  for (int i = 0; i < 10000; ++i) {    printf("Hi
"); }}int main() { clock_t start = clock(); really_expensive_function(); clock_t end = clock(); printf("Took %f seconds
", (((float)(end-start) / CLOCKS_PER_SEC))); return 0;}

clock_t is a typedef for long on my machine and is likely the same for yours. Despite that, you should still use clock_t as it may be different on different machines. We get the system time before and after the really expensive function and are able to get the amount of time in seconds.

You can try this example on repl-it.

Here is an output you might get

C Output

Benchmarking Software for Use

JavaScript:

C++:

Conclusion

In the end it's up to you how you choose to benchmark your code. Generally, you want to code your project before you benchmark it and if performance is really a concern then you can opt to use these benchmarking libraries or use a performance profile to find bottlenecks. I hope you learned something today :).


Original Link: https://dev.to/aboss123/benchmarking-code-2eog

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To