diff --git a/documentation/memory/step3/exercise/README.md b/documentation/memory/step3/exercise/README.md new file mode 100644 index 0000000..3bccadf --- /dev/null +++ b/documentation/memory/step3/exercise/README.md @@ -0,0 +1,4 @@ +# Tracing garbage collection exercices + +These scripts are materials for the [GC traces](https://nodejs.org/en/docs/guides/diagnostics/memory/using-gc-traces/) tutorial. + diff --git a/documentation/memory/step3/exercise/script-fix.mjs b/documentation/memory/step3/exercise/script-fix.mjs new file mode 100644 index 0000000..df7156f --- /dev/null +++ b/documentation/memory/step3/exercise/script-fix.mjs @@ -0,0 +1,34 @@ +import os from 'os'; +import fs from 'fs/promises'; + +let len = 1_000_000; +const fileName = `entries-${Date.now()}`; + +async function addEntry () { + const entry = { + timestamp: Date.now(), + memory: os.freemem(), + totalMemory: os.totalmem(), + uptime: os.uptime(), + }; + + await fs.appendFile(fileName, JSON.stringify(entry) + '\n'); +} + +async function summary () { + const stats = await fs.lstat(fileName); + console.log(`File size: ${stats.size} bytes! \n`); +} + +// execution +(async () => { + await fs.writeFile(fileName, "----START---\n"); + while (len > 0) { + await addEntry(); + process.stdout.write(`~~> ${len} entries to record\r`); + len--; + }; + + await summary(); +})(); + diff --git a/documentation/memory/step3/exercise/script.mjs b/documentation/memory/step3/exercise/script.mjs new file mode 100644 index 0000000..02ba922 --- /dev/null +++ b/documentation/memory/step3/exercise/script.mjs @@ -0,0 +1,31 @@ +import os from 'os'; + +let len = 1_000_000; +const entries = new Set(); + +function addEntry () { + const entry = { + timestamp: Date.now(), + memory: os.freemem(), + totalMemory: os.totalmem(), + uptime: os.uptime(), + }; + + entries.add(entry); +} + +function summary () { + console.log(`Total: ${entries.size} entries`); +} + +// execution +(() => { + while (len > 0) { + addEntry(); + process.stdout.write(`~~> ${len} entries to record\r`); + len--; + }; + + summary(); +})(); +