I'm learning how to measure performance, and would like to use some code that takes about 1-2 seconds to pute.
I've used this code below taken from Mozilla, but I wonder if someone could help me out with an operation that's a little more concise. It doesn't have to "make sense".
const iterations = 50;
const multiplier = 1000000000;
function calculatePrimes(iterations, multiplier) {
var primes = [];
for (var i = 0; i < iterations; i++) {
var candidate = i * (multiplier * Math.random());
var isPrime = true;
for (var c = 2; c <= Math.sqrt(candidate); ++c) {
if (candidate % c === 0) {
// not prime
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(candidate);
}
}
return primes;
}
function doPointlessComputationsWithBlocking() {
var primes = calculatePrimes(iterations, multiplier);
pointlessComputationsButton.disabled = false;
console.log(primes);
}
I'm learning how to measure performance, and would like to use some code that takes about 1-2 seconds to pute.
I've used this code below taken from Mozilla, but I wonder if someone could help me out with an operation that's a little more concise. It doesn't have to "make sense".
const iterations = 50;
const multiplier = 1000000000;
function calculatePrimes(iterations, multiplier) {
var primes = [];
for (var i = 0; i < iterations; i++) {
var candidate = i * (multiplier * Math.random());
var isPrime = true;
for (var c = 2; c <= Math.sqrt(candidate); ++c) {
if (candidate % c === 0) {
// not prime
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(candidate);
}
}
return primes;
}
function doPointlessComputationsWithBlocking() {
var primes = calculatePrimes(iterations, multiplier);
pointlessComputationsButton.disabled = false;
console.log(primes);
}
Share
Improve this question
asked Jun 27, 2020 at 7:32
Runner GastonRunner Gaston
1076 bronze badges
1
- 1 sort a very large array. you don't have to write your own sort because JS has a sort function. – user6713871 Commented Jun 27, 2020 at 7:39
1 Answer
Reset to default 9The easiest way to make an operation where the purpose is "it takes time", is to just do nothing but for a time period:
function wait(seconds) {
var start = new Date();
//empty while loop until the required amount of time has passed
while((new Date() - start) / 1000 < seconds);
}
var begin = performance.now();
console.log("start");
wait(2);
console.log("finish in", performance.now() - begin, "ms");
If you need it to be not as certain, you can add or modify the time to wait by a random amount:
function wait(seconds) {
// add or subtract up to 50%
seconds *= Math.random() + 0.5;
var start = new Date();
while((new Date() - start) / 1000 < seconds);
}
var begin = performance.now();
console.log("start");
wait(2);
console.log("finish in", performance.now() - begin, "ms");