sudo apt install mesa-common-dev libxi-dev // using Linux
npm
npm install gpu.js --save // OR yarn add gpu.js
在你的Node项目中要导入GPU.js。
import { GPU } from ('gpu.js')
// OR const { GPU } = require('gpu.js')
const gpu = new GPU();
乘法演示
在下面的示例中,计算是在GPU上并行完成的。
首先,生成大量数据。
const getArrayValues = () => {
// 在此处创建2D arrary const values = [[], []]
// 将值插入第一个数组 for (let y = 0; y < 600; y++){ values[0].push([]) values[1].push([])
// 将值插入第二个数组 for (let x = 0; x < 600; x++){ values\[0\][y].push(Math.random()) values\[1\][y].push(Math.random()) } }
// 返回填充数组 return values }
创建内核(运行在GPU上的函数的另一个词)。
const gpu = new GPU();
// 使用 `createKernel()` 方法将数组相乘 const multiplyLargeValues = gpu.createKernel(function(a, b) { let sum = 0; for (let i = 0; i < 600; i++) { sum += a\[this.thread.y\][i] * b\[i\][this.thread.x]; } return sum; }).setOutput([600, 600])
使用矩阵作为参数调用内核。
const largeArray = getArrayValues() const out = multiplyLargeValues(largeArray[0], largeArray[1])