speedtest.js 831 B

12345678910111213141516171819202122232425262728
  1. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms));
  2. const speedtest = async (getPromise, count, parallel= 1) => {
  3. const t0 = performance.now();
  4. for (let i = 1; i <= count; i++) {
  5. let arr = [];
  6. for (let j = 1; j <= parallel; j++) {
  7. arr.push(getPromise());
  8. }
  9. await Promise.all(arr);
  10. }
  11. const t1 = performance.now();
  12. const parallelDuration = parallel * count;
  13. const duration = t1 - t0;
  14. const parallelSpeed = parallelDuration / duration;
  15. const queryDuration = duration / count;
  16. const querySpeed = count / duration;
  17. return {
  18. duration,
  19. querySpeed,
  20. queryDuration,
  21. parallelSpeed,
  22. parallelDuration
  23. }
  24. }
  25. speedtest(() => delay(1000), 10, 10 ).then(result => console.log(result));
  26. speedtest(() => fetch('http://swapi.dev/api/people/1').then(res => res.json()), 2, 2);