You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In Node.js, it's crucial to measure the execution time of your code, especially when dealing with time-consuming operations or performance-critical tasks. This ensures that your application runs efficiently and helps you identify potential bottlenecks for optimization. To achieve this, Node.js provides the console.time() and console.timeEnd() functions, allowing you to precisely measure how long a specific portion of your code takes to execute.
Copy file name to clipboardExpand all lines: README.md
+42Lines changed: 42 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4956,6 +4956,48 @@ console.log(x); // 10
4956
4956
<b><a href="#table-of-contents">↥ back to top</a></b>
4957
4957
</div>
4958
4958
4959
+
# Timing Function Execution in Node.js
4960
+
4961
+
You can check the runtime of a function in Node.js by using the `console.time()` and `console.timeEnd()` functions. Here's an example with an explanation:
4962
+
4963
+
```javascript
4964
+
functionmyFunction() {
4965
+
console.log("Function started");
4966
+
4967
+
// Start the timer
4968
+
console.time("myFunction");
4969
+
4970
+
// Simulate some time-consuming task
4971
+
for (let i =0; i <1000000000; i++) {
4972
+
// Do some work
4973
+
}
4974
+
4975
+
// End the timer
4976
+
console.timeEnd("myFunction");
4977
+
4978
+
console.log("Function ended");
4979
+
}
4980
+
4981
+
myFunction();
4982
+
4983
+
4984
+
## In this example:
4985
+
4986
+
- We use `console.log` to print a message indicating the start of the function.
4987
+
- We start a timer named "myFunction" using `console.time("myFunction")`.
4988
+
- We simulate a time-consuming task by running a loop.
4989
+
- After the loop is finished, we end the timer using `console.timeEnd("myFunction")`.
4990
+
- Finally, we use `console.log` to print a message indicating the end of the function.
4991
+
4992
+
```javaScript
4993
+
Function started
4994
+
myFunction: 5431.709ms
4995
+
Function ended
4996
+
4997
+
The time in milliseconds (ms) represents the runtime of the function `myFunction`. You can use this approach to measure the runtime of specific parts of your code to identify performance bottlenecks or optimize your code.
4998
+
4999
+
5000
+
4959
5001
#### Q. What is Distributed Denial of Service (DDoS) attacks and how to secure NodeJS REST API from it?
4960
5002
#### Q. What are SOLID principles?
4961
5003
#### Q. How to develop Node.js app using SOLID principles?
0 commit comments