'在瀏覽器中實現GPU加速的JavaScript'

"
"
在瀏覽器中實現GPU加速的JavaScript

gpu.js

GPU加速JavaScript

GPU.js是用於Web和節點的JavaScript的GPGPU(GPU上的通用計算)的JavaScript加速庫。

GPU.js自動將簡單的JavaScript函數轉換為著色器語言並編譯它們,以便它們在GPU上運行。

如果GPU不可用,這些功能仍將在常規JavaScript中運行。

安裝

在Linux上,確保安裝了正確的擴展:( sudo apt install mesa-common-dev libxi-dev根據您的發行版進行調整)

NPM

npm install gpu.js --save

語法支持

gpu.js依賴於內核函數僅使用合法JavaScript語法的子集的假設:

  • 1D,2D,3D數組或僅作為內核輸入的數字
  • 1D,2D,3D數組作為內核輸出
  • 數字變量
  • 自定義和自定義本地function小號
  • 算術運算(+,+=,-,*,/,%)
  • Javascript數學函數(Math.floor()等)
  • 循環
  • if和else陳述
  • const 和 let
  • 閉包沒有捕獲變量

Browser

<script src="dist/gpu-browser.min.js"></script>
<script>
// GPU is a constructor and namespace for browser
const gpu = new GPU();
const multiplyMatrix = gpu.createKernel(function(a, b) {
let sum = 0;
for (let i = 0; i < 512; i++) {
sum += a[this.thread.y][i] * b[i][this.thread.x];
}
return sum;
}).setOutput([512, 512]);
const c = multiplyMatrix(a, b);
</script>

Node

const { GPU } = require('gpu.js');
const gpu = new GPU();
const multiplyMatrix = gpu.createKernel(function(a, b) {
let sum = 0;
for (let i = 0; i < 512; i++) {
sum += a[this.thread.y][i] * b[i][this.thread.x];
}
return sum;
}).setOutput([512, 512]);
const c = multiplyMatrix(a, b);

Typescript

import { GPU } from 'gpu.js';
const gpu = new GPU();
const multiplyMatrix = gpu.createKernel(function(a: number[][], b: number[][]) {
let sum = 0;
for (let i = 0; i < 512; i++) {
sum += a[this.thread.y][i] * b[i][this.thread.x];
}
return sum;
}).setOutput([512, 512]);
const c = multiplyMatrix(a, b) as number[][];

更多使用方法 要查看 官方文檔

github

https://github.com/gpujs/gpu.js

您知道哪些好用的JS 擴展包,歡迎評論分享,共同探討學習

如果覺得文章能夠對您有所幫助,可以關注我,你的支持會鼓勵我不斷分享更多更好的優質文章。

"

相關推薦

推薦中...