NodeJS Program to Timing A Function with Explanation
NodeJS
Medium
Node Basics & Modules
29 views
1 min read
82 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around function, hrtime, bigint. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Measure how long a function takes using process.hrtime.bigint().
Input Format
No input.
Output Format
Print ms.
Constraints
Use hrtime.bigint for better precision.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
function work() {
let s = 0;
for (let i = 0; i < 300000; i++) s += i % 7;
return s;
}
const start = process.hrtime.bigint();
work();
const end = process.hrtime.bigint();
const ms = Number(end - start) / 1e6;
console.log('Time: ' + Math.round(ms) + 'ms');
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Measure how long a function takes using process.hrtime.bigint().
Input / Output
Constraints
Use hrtime.bigint for better precision.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
function work() {
let s = 0;
for (let i = 0; i < 300000; i++) s += i % 7;
return s;
}
const start = process.hrtime.bigint();
work();
const end = process.hrtime.bigint();
const ms = Number(end - start) / 1e6;
console.log('Time: ' + Math.round(ms) + 'ms');
Solutions (0)
No solutions submitted yet. Be the first!