Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Timing-Functions/MeasureExecutionTime.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Function that measures the execution time of a given function.
* @param {Function} func - The function to be measured.
* @returns {number} - The time taken in milliseconds.
*/
const measureExecutionTime = (func) => {
if (typeof func !== 'function') {
throw new TypeError('Input should be a function.');
}

const startTime = performance.now();
func();
const endTime = performance.now();

return endTime - startTime;
};

export { measureExecutionTime };

21 changes: 21 additions & 0 deletions Timing-Functions/test/MeasureExecutionTime.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { measureExecutionTime } from '../MeasureExecutionTime';

describe('Measure Execution Time', () => {
it('measures the execution time of a function', () => {
const testFunction = () => {
let sum = 0;
for (let i = 0; i < 1000000; i++) {
sum += i;
}
};

const executionTime = measureExecutionTime(testFunction);
expect(executionTime).toBeGreaterThan(0); // Ensure it took some time
});

it('throws a type error if not given a function', () => {
expect(() => {
measureExecutionTime('notAFunction');
}).toThrow('Input should be a function.');
});
});