More benchmarks

This commit is contained in:
Andrew Morris
2023-06-21 16:17:52 +10:00
parent a2a940b5cb
commit 53695d7948
7 changed files with 98 additions and 7 deletions

View File

@@ -0,0 +1,58 @@
export default function quickSort<T>(vals: T[], cmp: (a: T, b: T) => number) {
// Demonstrates the ability to do in-place updates in ValueScript.
//
// There's only one reference to `vals`, so we can mutate it in-place
// without violating value semantics.
//
// More on quickSort:
// https://www.youtube.com/watch?v=Hoixgm4-P4M
const len = vals.length;
let ranges: [number, number][] = [[0, len - 1]];
while (true) {
const range = ranges.shift();
if (!range) {
return vals;
}
const [start, end] = range;
if (end - start <= 0) {
continue;
}
let i = start;
let j = end;
let pivotIndex = Math.floor((i + j) / 2);
[vals[pivotIndex], vals[j]] = [vals[j], vals[pivotIndex]];
const pivot = vals[j];
j--;
while (true) {
while (cmp(vals[i], pivot) < 0) {
i++;
}
while (cmp(vals[j], pivot) > 0) {
j--;
}
if (i < j) {
[vals[i], vals[j]] = [vals[j], vals[i]];
i++;
j--;
continue;
}
[vals[i], vals[end]] = [vals[end], vals[i]];
ranges.push([start, i - 1]);
ranges.push([i + 1, end]);
break;
}
}
}

View File

@@ -0,0 +1,12 @@
export default function* randish() {
let x = 0.123;
while (true) {
x -= (x * x + 1) / (2 * x + 0.1);
x -= (x * x + 1) / (2 * x + 0.1);
x -= (x * x + 1) / (2 * x + 0.1);
const y = 1000 * x;
yield y - Math.floor(y);
}
}

View File

@@ -0,0 +1,7 @@
//! bench()
import { Range_primes } from "./helpers/range.ts";
export default function main() {
return Range_primes().at(999);
}

View File

@@ -1,5 +1,5 @@
import { Range_primes } from "../helpers/range.ts";
export default function main() {
return Range_primes().at(10_000);
return Range_primes().at(1_000);
}

View File

@@ -0,0 +1,17 @@
//! bench()
import quickSort from "./helpers/quickSort.ts";
import randish from "./helpers/randish.ts";
import { Range_from } from "./helpers/range.ts";
export default function main() {
let nums = [
...Range_from(randish())
.map((x) => Math.floor(5_000 * x))
.limit(5_000),
];
nums = quickSort(nums, (a, b) => a - b);
return nums;
}