Skip to content

Commit 5b0171f

Browse files
committed
feat: implement basic timing functionality
1 parent 6c9cce7 commit 5b0171f

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

lib/time.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* Measures the running time of a function, in milliseconds
3+
* @param {function} fun Function to be timed.
4+
* @param {any[]} args Function arguments.
5+
* @returns {number} Total run time of the function, in milliseconds.
6+
*/
7+
const timeFun = (fun, args) => {
8+
const start = performance.now()
9+
fun(...args)
10+
const end = performance.now()
11+
12+
return end - start
13+
}
14+
15+
/**
16+
* Shuffles array, in place.
17+
* @param {any[]} arr Array to be shuffled.
18+
* @returns {any[]} Reference to the input array, now shuffled.
19+
*/
20+
const shuffle = (arr) => {
21+
for (let idx = arr.length - 1; idx >= 0; idx--) {
22+
const swapIdx = Math.floor(Math.random() * (idx + 1))
23+
;[arr[idx], arr[swapIdx]] = [arr[swapIdx], arr[idx]]
24+
}
25+
26+
return arr
27+
}
28+
29+
const timeRepo = (algos, args, runs, id) => {
30+
const times = {}
31+
for (const algo of algos) {
32+
times[algo.id] = 0
33+
}
34+
35+
for (let r = 0; r < runs; r++) {
36+
shuffle(algos)
37+
38+
for (const algo of algos) {
39+
times[algo.id] += timeFun(algo.fun, args)
40+
}
41+
}
42+
43+
const sortedTimes =
44+
Object
45+
.entries(times)
46+
.sort((a, b) => a[1] - b[1])
47+
48+
return { id, sortedTimes, args, runs }
49+
}
50+
51+
module.exports = {
52+
timeRepo
53+
}

0 commit comments

Comments
 (0)