// Example for CPU profiling in Node.js
// This file contains CPU-intensive operations we can profile
// Function with exponential complexity (inefficient Fibonacci)
function inefficientFibonacci(n) {
if (n <= 1) return n;
return inefficientFibonacci(n - 1) + inefficientFibonacci(n - 2);
}
// More efficient linear Fibonacci
function efficientFibonacci(n) {
if (n <= 1) return n;
let a = 0, b = 1, temp;
for (let i = 2; i <= n; i++) {
temp = a + b;
a = b;
b = temp;
}
return b;
}
// Inefficient string builder function
function inefficientStringBuilder(size) {
let result = '';
for (let i = 0; i < size; i++) {
result += 'a'; // Creates a new string each time
}
return result;
}
// More efficient string builder function
function efficientStringBuilder(size) {
const array = new Array(size);
for (let i = 0; i < size; i++) {
array[i] = 'a';
}
return array.join('');
}
// Inefficient array search
function inefficientArraySearch(array, item) {
for (let i = 0; i < array.length; i++) {
if (array[i] === item) {
return true;
}
}
return false;
}
// Simulating a workload to profile
function runWorkload() {
console.log('Starting workload...');
// Create a large array
const start = Date.now();
const size = 100000;
const array = new Array(size);
for (let i = 0; i < size; i++) {
array[i] = Math.floor(Math.random() * size);
}
// CPU-intensive operations
console.log('Running inefficient string builder...');
inefficientStringBuilder(10000);
console.log('Running inefficient Fibonacci...');
inefficientFibonacci(30);
console.log('Running searches...');
for (let i = 0; i < 1000; i++) {
inefficientArraySearch(array, Math.floor(Math.random() * size));
}
// For comparison, run the efficient versions
console.log('Running efficient string builder...');
efficientStringBuilder(10000);
console.log('Running efficient Fibonacci...');
efficientFibonacci(30);
console.log(`Workload completed in ${Date.now() - start}ms`);
}
// Run the workload
runWorkload();
/*
TO PROFILE THIS APPLICATION:
Method 1: Using the built-in Node.js profiler:
1. Run: node --prof demo_debugging_cpu_profiling.js
2. This generates an isolate-v8.log file
3. Process it: node --prof-process isolate-v8.log > processed.txt
4. Examine processed.txt to see where time is spent
Method 2: Using Chrome DevTools:
1. Run: node --inspect-brk demo_debugging_cpu_profiling.js
2. Open Chrome and navigate to chrome://inspect
3. Click on "Open dedicated DevTools for Node"
4. In the Performance tab, click Record
5. Click the Resume script execution button
6. After the script completes, stop recording
7. Analyze the flame chart to see CPU usage
Method 3: Using Clinic.js:
1. Install: npm install -g clinic
2. Run: clinic doctor -- node demo_debugging_cpu_profiling.js
3. View the generated HTML report
*/