const { GPU } = require('gpu.js'); const gpu = new GPU(); const generateData = (days) => { const data = []; for (let y = 0; y < days; y++) data.push(Math.random()); return data; } const data = generateData(1000000);
const GPUMA = gpu.createKernel(function (a,windowSize) { let sum = 0; for (let i = 0; i < windowSize; i++) { sum += a[this.thread.x+i]; } return sum/windowSize; }).setOutput([data.length]) //setOutput需要在createKernel之后立刻调用, //而此时还没有调用核函数因此也不知道将会使用的窗口大小,所以只能按照最大窗口大小来设置输出,调用方在接受到结果后需要自行截取
function calculateMA(data,windowSize) { const outputLength = data.length - windowSize + 1; const ma = new Array(outputLength);
for (let i = 0; i < outputLength; i++) { let sum = 0; for (let j = 0; j < windowSize; j++) { sum += data[i + j]; } ma[i] = sum / windowSize; }