1

I am trying to implement a timer in javascript using web workers. I wrote the following code. But it's not working. Can someone point out why it's not working? I don't have much experience with javascript. So, it would be great if someone explains the reason in great detail.

Here's what I'm trying to do:

First creating a sharedArrayBuffer and a worker thread. And creating another array, on which, I will do some work and want to count the time. Then sending the sharedArrayBuffer to worker thread which increments the first value in the array in a for loop. Finally, I am reading that value in the main.js and I'm getting 0 every time.

main.js

        var buffer = new SharedArrayBuffer(1024);
        var i;
        var uint32 = new Uint32Array(buffer);
        var myWorker = new Worker('worker.js');
        var array = new Uint32Array(8);
        array[0] = 0;
        console.log(Atomics.load(uint32,0),array[0]);

        myWorker.postMessage(buffer);

        for(i=0;i<300000000;i++) {
            array[0] += i;
        }

        console.log(i,Atomics.load(uint32,0),array[0]);

worker.js

        onmessage = function(buffer) {
        console.log('from worker');
        var uint32 = new Uint32Array(buffer.data);

        for(i=0; ;i++) {
            uint32[0] += 1;
        };
        }
Maverick_284
  • 41
  • 1
  • 7
  • It's working fine in chrome. I didn't get any errors. As I said, I want to find the time elapsed while executing certain code and I'm getting 0 always. – Maverick_284 Oct 08 '19 at 20:09

1 Answers1

1

You should not be using code like this to try and determine how long code takes to run. It's non-sensical because incrementing the count in an array is not tied to time or any unit of measurement. Instead, there are APIs which can be used to evaluate performance, such as console.time():

    onmessage = function(buffer) {
      console.time('TimeSpentInWorker');

      // Your code...

      console.timeEnd('TimeSpentInWorker');
    };

You could also compare the difference between calling Date.now() twice or look into the Performance API.

skyline3000
  • 7,639
  • 2
  • 24
  • 33
  • If we assume for loop will be executed in 5 nano seconds i.e, 10 instructions for a 2 GHz CPU, that we can consider as an unit of measurement. I want a high resolution timer with precision in nano seconds. – Maverick_284 Oct 08 '19 at 20:30
  • 1
    You should never make assumptions about processor speed and how that translates to a JavaScript engine parsing, compiling, and running your code. Not many JavaScript environments will actually provide you a high-resolution timestamp, see this question: https://stackoverflow.com/questions/6002808/is-there-any-way-to-get-current-time-in-nanoseconds-using-javascript It is most likely only available (if at all) through the Performance API in the link in my answer. – skyline3000 Oct 08 '19 at 20:50