使用GPU.js改善JavaScript性能


你是否曾經嘗試過運行復雜的計算,卻發現它需要花費很長時間,並且拖慢了你的進程?

有很多方法可以解決這個問題,例如使用 web worker 或后台線程。GPU 減輕了 CPU 的處理負荷,給了 CPU 更多的空間來處理其他進程。同時,web worker 仍然運行在 CPU 上,但是運行在不同的線程上。

在該初學者指南中,我們將演示如何使用GPU.js執行復雜的數學計算並提高 JavaScript 應用的性能。

1.什么是 GPU.js?

GPU.js 是一個針對 Web 和 Node.js 構建的 JavaScript 加速庫,用於在圖形處理單元(GPGPU)上進行通用編程,它使你可以將復雜且耗時的計算移交給 GPU 而不是 CPU,以實現更快的計算和操作。還有一個備用選項:在系統上沒有 GPU 的情況下,這些功能仍將在常規 JavaScript 引擎上運行。

當你要執行復雜的計算時,實質上是將這種負擔轉移給系統的 GPU 而不是 CPU,從而增加了處理速度和時間。

高性能計算是使用 GPU.js 的主要優勢之一。如果你想在瀏覽器中進行並行計算,而不了解 WebGL,那么 GPU.js 是一個適合你的庫。

2.為什么要使用 GPU.js

為什么要使用 GPU 執行復雜的計算的原因不勝枚舉,有太多的原因無法在一篇文章中探討。以下是使用 GPU 的一些最值得注意的好處。

  • GPU 可用於執行大規模並行 GPGPU 計算。這是需要異步完成的計算類型
  • 當系統中沒有 GPU 時,它會優雅地退回到 JavaScript
  • GPU 當前在瀏覽器和 Node.js 上運行,非常適合通過大量計算來加速網站
  • GPU.js 是在考慮 JavaScript 的情況下構建的,因此這些功能均使用合法的 JavaScript 語法

如果你認為你的處理器可以勝任,你不需要 GPU.js,看看下面這個 GPU 和 CPU 運行計算的結果。

 

 

如你所見,GPU 比 CPU 快 22.97 倍。

3.GPU.js 的工作方式

考慮到這種速度水平,JavaScript 生態系統仿佛得到了一個可以乘坐的火箭。GPU 可以幫助網站更快地加載,特別是必須在首頁上執行復雜計算的網站。你不再需要擔心使用后台線程和加載器,因為 GPU 運行計算的速度是普通 CPU 的 22.97 倍。

gpu.createKernel 方法創建了一個從 JavaScript 函數移植過來的 GPU 加速內核。

與 GPU 並行運行內核函數會導致更快的計算速度——快 1-15 倍,這取決於你的硬件。

4.GPU.js 入門

為了展示如何使用 GPU.js 更快地計算復雜的計算,讓我們快速啟動一個實際的演示。

安裝

sudo apt install mesa-common-dev libxi-dev  // using Linux

 

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]
);

 

輸出

console.log(out\[y\][x]) // 將元素記錄在數組的第x行和第y列
console.log(out\[10\][12]) // 記錄輸出數組第10行和第12列的元素

 

5.運行 GPU 基准測試

你可以按照GitHub上指定的步驟運行基准測試。

 
npm install @gpujs/benchmark

const benchmark = require('@gpujs/benchmark')

const benchmarks = benchmark.benchmark(options);

 

options 對象包含可以傳遞給基准的各種配置。

前往 GPU.js 官方網站查看完整的計算基准,這將幫助你了解使用 GPU.js 進行復雜計算可以獲得多少速度。

6.如何設置 GPU.js?

為您的項目安裝 GPU.js 與其他的 JavaScript 庫類似。

對於 Node 項目

npm install gpu.js --save
or
yarn add gpu.js
import { GPU } from ('gpu.js')
--- or ---
const { GPU } = require('gpu.js')
--- or ---
import { GPU } from 'gpu.js'; // Use this for TypeScript
const gpu = new GPU();

對於 Bowsers

在本地下載 GPU.js 或使用其 CDN。

<script src="dist/gpu-browser.min.js"></script>
--- or ---
<script
  src="https:/
/unpkg.com/gpu.js@latest/dist/gpu- browser.min.js">
</script>
<script
  rc="
https://cdn.jsdelivr.net/npm/gpu.js@latest/dist/gpu-browser.min.js">
</script>
<script>
 const gpu = new GPU();
 ...
</
script>

注意:

如果你使用的是 Linux,你需要確保你安裝了正確的文件,運行:sudo apt install mesa-common-dev libxi-dev

這就是你需要知道的關於安裝和導入 GPU.js 的情況。

現在,你可以開始在你的應用程序中使用 GPU 編程。

此外,我強烈建議理解 GPU.js 的基本功能和概念。所以,讓我們從 GPU.js 的一些基礎知識開始。

創建函數

你可以在 GPU.js 中定義函數以在 GPU 中運行,使用一般的 JavaScript 語法。

const exampleKernel = gpu.createKernel(function() {
    ...
}, settings);

上面的代碼樣本顯示了一個 GPU.js 函數的基本結構。我將該函數命名為 exampleKernel。正如你所看到的,我使用了 createKernel 函數,利用 GPU 進行計算。

另外,定義輸出的大小是必須的。在上面的例子中,我使用了一個名為 settings 的參數來指定輸出大小。

const settings = {
    output: [100]
};

內核函數的輸出可以是 1D、2D 或 3D,這意味着它最多可以有 3 個線程。你可以使用 this.thread 命令在內核中訪問這些線程。

  • 1D : [長度] - 值[this.thread.x]
  • 2D : [寬度,高度] - 值[this.thread.y][this.thread.x]
  • 3D: [寬度,高度,深度] - 值[this.thread.z][this.thread.y][this.thread.x]。

最后,創建的函數可以像其他的 JavaScript 函數一樣使用函數名來調用:exampleKernel()

內部支持的變量

Number

你可以在 GPU.js 函數中使用任何整數或浮點數。

const exampleKernel = gpu.createKernel(function() {
 const number1 = 10;
 const number2 = 0.10;
 return number1 + number2;
}, settings);

Boolean

GPU.js 中也支持布爾值,與 JavaScript 類似。

const kernel = gpu.createKernel(function() {
  const bool = true;
  if (bool) {
    return 1;
  }else{
    return 0;
  }
},settings);

Arrays

你可以在內核函數中定義任何大小的數字數組,並返回它們。

const exampleKernel = gpu.createKernel(function() {
 const array1 = [0.0110.110];
 return array1;
}, settings);

Functions

在內核函數中使用私有函數,在 GPU.js 中也是允許的。

const exampleKernel = gpu.createKernel(function() {
  function privateFunction() {
    return [0.0110.110];
  }
  return privateFunction();
}, settings);

支持的輸入類型

除了上述變量類型外,你還可以向內核函數傳遞幾種輸入類型。

Numbers

與變量聲明類似,你可以向內核函數傳遞整數或浮點數,如下所示。

const exampleKernel = gpu.createKernel(function(x{
 return x;
}, settings);
exampleKernel(25);

1D,2D, or 3D Array of Numbers

你可以將 Array、Float32Array、Int16Array、Int8Array、Uint16Array、uInt8Array 等數組類型傳入 GPU.js 內核。

const exampleKernel = gpu.createKernel(function(x{
 return x;
}, settings);
exampleKernel([123]);

預扁平化的 2D 和 3D 數組也被內核函數所接受。這種方法使上傳的速度更快,你必須使用 GPU.js 的輸入選項來實現這一點。

const { input } = require('gpu.js');
const value = input(flattenedArray, [width, height, depth]);

HTML Images

與傳統的 JavaScript 相比,將圖像傳遞到函數中是我們在 GPU.js 中可以看到的一個新東西。使用 GPU.js,你可以將一個或多個 HTML 圖像作為數組傳遞給內核函數。

//Single Image
const kernel = gpu.createKernel(function(image{
    ...
})
  .setGraphical(true)
  .setOutput([100100]);

const image = document.createElement('img');
image.src = 'image1.png';
image.onload = () => {
  kernel(image);
  document.getElementsByTagName('body')[0].appendChild(kernel.canvas);
};
//Multiple Images
const kernel = gpu.createKernel(function(image{
    const pixel = image[this.thread.z][this.thread.y][this.thread.x];
    this.color(pixel[0], pixel[1], pixel[2], pixel[3]);
})
  .setGraphical(true)
  .setOutput([100100]);

const image1 = document.createElement('img');
image1.src = 'image1.png';
image1.onload = onload;
....
//add another 2 images
....
const totalImages = 3;
let loadedImages = 0;
function onload() {
  loadedImages++;
  if (loadedImages === totalImages) {
    kernel([image1, image2, image3]);
     document.getElementsByTagName('body')[0].appendChild(kernel.canvas);
  }
};

除了上述配置外,還有許多令人興奮的事情可以用 GPU.js 進行實驗。你可以在其文檔中找到它們。既然你現在了解了幾種配置,讓我們用 GPU.js 寫一個函數並比較其性能。

7.使用 GPU.js 的第一個功能

通過結合我們之前討論的所有內容,我寫了一個小型的 angular 應用程序,通過將兩個有 1000 個元素的數組相乘來比較 GPU 和 CPU 的計算性能。

第 1 步,生成 1000 個元素的數組的函數

我將生成一個每個元素有 1000 個數字的 2D 數組,並在接下來的步驟中使用它們進行計算。

generateMatrices() {
 this.matrices = [[], []];
 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)
  }
 }
}

第 2 步,內核函數

這是這個應用程序中最關鍵的函數,因為所有的 GPU 計算都發生在這里。

在這里,multiplyMatrix 函數將接收兩個數字數組和矩陣的大小作為輸入。

然后,它將把兩個數組相乘並返回總和,同時使用性能 API 測量時間。

gpuMultiplyMatrix() {
  const gpu = new GPU();
  const multiplyMatrix = gpu.createKernel(function (a: number[][], b: number[][], matrixSize: number{
   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(this.matrices[0],  this.matrices[1], this.matrixSize);

  const endTime = performance.now();
  this.gpuTime = (endTime - startTime) + " ms";

  console.log("GPU TIME : "this.gpuTime);
  this.gpuProduct = resultMatrix as number[][];
}

步驟 3,CPU 乘法函數。

這是一個傳統的 TypeScript 函數,用於測量相同數組的計算時間。

cpuMutiplyMatrix() {
  const startTime = performance.now();
  const a = this.matrices[0];
  const b = this.matrices[1];
  let productRow = Array.apply(nullnew Array(this.matrixSize)).map(Number.prototype.valueOf, 0);
  let product = new Array(this.matrixSize);

  for (let p = 0; p < this.matrixSize; p++) {
    product[p] = productRow.slice();
  }

  for (let i = 0; i < this.matrixSize; i++) {
    for (let j = 0; j < this.matrixSize; j++) {
      for (let k = 0; k < this.matrixSize; k++) {
        product[i][j] += a[i][k] * b[k][j];
      }
    }
  }
  const endTime = performance.now();
  this.cpuTime = (endTime — startTime) + “ ms”;
  console.log(“CPU TIME : “+ this.cpuTime);
  this.cpuProduct = product;
}

8.CPU vs GPU,性能比較

現在是時候看看圍繞着 GPU.js 和 GPU 計算的所有討論是否真實。由於我在上一節中創建了一個 Angular 應用程序,所以我用它來測量性能。

 

 

 

 


CPU vs GPU — Execution Time

你可以清楚地看到,GPU 編程的計算只花了 799ms,而 CPU 花了 7511ms,這幾乎是 10 倍的時間。

我沒有就此罷休,通過改變數組大小,對同樣的測試進行了幾個循環。

 

 


CPU vs GPU

首先,我試着用較小的數組大小,我注意到 CPU 比 GPU 花費的時間要少。例如,當我把數組大小減少到 10 個元素時,CPU 只花了 0.14ms,而 GPU 花了 108ms。

但隨着數組大小的增加,GPU 和 CPU 所花的時間有明顯的差距。正如你在上圖中看到的,GPU 是贏家。

10.結論

根據我使用 GPU.js 的實驗,它可以提高 JavaScript 應用程序的性能。

但是,我們必須注意只將 GPU 用於復雜的任務。否則,我們將浪費資源,最終會降低應用程序的性能,

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM