- gpu相比于cpu,有强大的内存访问带宽和并行单元运算的能力
- WebGL GPU.js
const { GPU } = require("gpu.js")
function generateMatrices() {
this.matrices = [[], []]
this.matrixSize = 4
for (let y = 0; y < this.matrixSize; y++) {
this.matrices[0].push([])
this.matrices[1].push([])
for (let x = 0; x < this.matrixSize; x++) {
const value1 = parseInt((Math.random() * 10).toString())
const value2 = parseInt((Math.random() * 10).toString())
this.matrices[0][y].push(value1)
this.matrices[1][y].push(value2)
}
}
}
var m = new generateMatrices()
function gpuMultiplyMatrix(m) {
const gpu = new GPU()
this.matrixSize = m.matrixSize
const multiplyMatrix = gpu
.createKernel(function (a, b, matrixSize) {
let sum = 0
for (let i = 0; i < matrixSize; i++) {
sum += a[this.thread.y][i] * b[i][this.thread.x]
}
return sum
})
.setOutput([this.matrixSize, this.matrixSize])
const startTime = performance.now()
const resultMatrix = multiplyMatrix(
m.matrices[0],
m.matrices[1],
this.matrixSize
)
// console.log(resultMatrix, "resultMatrix")
const endTime = performance.now()
this.gpuTime = endTime - startTime + " ms"
console.log("GPU TIME : " + this.gpuTime)
}
gpuMultiplyMatrix(m)
cpuMutiplyMatrix(m)
function cpuMutiplyMatrix(m) {
const startTime = performance.now()
const a = m.matrices[0]
const b = m.matrices[1]
let productRow = Array.apply(null, new Array(m.matrixSize)).map(
Number.prototype.valueOf,
0
)
let product = new Array(m.matrixSize)
for (let p = 0; p < m.matrixSize; p++) {
product[p] = productRow.slice()
}
for (let i = 0; i < m.matrixSize; i++) {
for (let j = 0; j < m.matrixSize; j++) {
for (let k = 0; k < m.matrixSize; k++) {
product[i][j] += a[i][k] * b[k][j]
}
}
}
console.log(product)
const endTime = performance.now()
this.cpuTime = endTime - startTime + "ms"
console.log("CPU TIME : " + this.cpuTime)
}
const { GPU } = require("gpu.js")
const gpu = new GPU()
let kernel = gpu
.createKernel(function (a, b, c) { //1. 函数体内不能用a.length,不被识别,应该作为参数传进来
let sum = 0
for (var i = 0; i < c; i++) { //c 如果大于1000,则i只能循环到999,搞不懂
sum += a[0] + b[0]
}
return sum
})
.setOutput([1]) //2. x,y,z 对应for(z){for(y){for(x){ 函数体内的this.thread.x|y|z }}}
let a = new Array(100)
let b = new Array(100)
for (let i = 0; i < 100; i++) {
a[i] = Math.random()
b[i] = Math.random()
}
console.log(a.length, "length")
console.time()
let result = kernel(a, b, a.length)
console.log(result)
console.timeEnd()
let kernel = gpu
.createKernel(function (a, b, cc) {
var sum = 0
do {
++sum
} while (sum != this.constants.size)
do {
++sum
} while (sum != 10000)
do {
++sum
} while (sum != 10000)
return sum
},{
constants:{size:2000}, // 传参
pipeline :true, //搞不懂
loopMaxIterations :2000, // 设置循环限制,默认1000
output:[1]
})
console.log( kernel(1,1,1).toArray())
网友评论