Skip to content

Commit f407313

Browse files
authored
Timing function execution
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.
1 parent cbc1015 commit f407313

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

README.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4956,6 +4956,48 @@ console.log(x); // 10
49564956
<b><a href="#table-of-contents">↥ back to top</a></b>
49574957
</div>
49584958
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+
function myFunction() {
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+
49595001
#### Q. What is Distributed Denial of Service (DDoS) attacks and how to secure NodeJS REST API from it?
49605002
#### Q. What are SOLID principles?
49615003
#### Q. How to develop Node.js app using SOLID principles?

0 commit comments

Comments
 (0)