E
E
Eldrich2018-05-22 13:16:12
JavaScript
Eldrich, 2018-05-22 13:16:12

How to optimize JS code to speed up work?

Good day.
The task is to calculate the values ​​​​of the matrix 52000 by 52000 on JS.
The value in each cell is the result of calculating the Cosine Proximity of 300 vectors.
To speed up the calculations, I use GPUJS:

gpu.addFunction(function mF(a, b) {
            return a * b;
        });
const f3 = gpu.createKernel(function(inp) {

            var a = 0
            var b = 0
            var c = 0
            for (var i = 0; i < 300; i++) {
                a += mF(inp[this.thread.y][i], inp[this.thread.x][i])
                b += mF(inp[this.thread.y][i], inp[this.thread.y][i])
                c += mF(inp[this.thread.x][i], inp[this.thread.x][i])
            }

            return a / (Math.pow(b, 0.5) * Math.pow(c, 0.5));

        }).setOutput([52000, 52000])

Can this be optimized?
On average, it takes 7ms to calculate all the cosine values ​​from one vector to all the others (36ms without a GPU), which is almost 6 minutes to calculate the entire matrix. I am a layman in JS and, most likely, I do not see obvious ways to optimize the code to speed up its work.
The script also dies safely when calculating the entire huge matrix, you have to count it in pieces of 1000 vectors.
Thanks

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Andrey Fedoseev, 2018-05-22
@itlen

The script also dies safely when calculating the entire huge matrix, you have to count it in pieces of 1000 vectors.

Maybe it makes sense to send these pieces to SharedWorker

S
string15, 2018-05-22
@string15

You can try WebAssembly

D
dom1n1k, 2018-05-23
@dom1n1k

I have never dealt with GPUJS, but what catches your eye from general considerations is to cache indexes and be sure to replace pow 0.5 with sqrt (and with one, not two!).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question