如何使用GPU改善JavaScript性能

开发 前端
作为开发者,我们总是寻找机会来提高应用程序的性能。当涉及到网络应用时,我们主要在代码中进行这些改进。但是,你有没有想过将 GPU 的力量结合到你的网络应用中来提高性能?本文将向你介绍一个名为 GPU.js 的 JavaScript 加速库,并告诉你如何改进复杂的计算。

[[402117]]

本文转载自微信公众号「TianTianUp」,作者小弋。转载本文请联系TianTianUp公众号。

正文

用 GPU.js 使你的应用程序快 10 倍。

作为开发者,我们总是寻找机会来提高应用程序的性能。当涉及到网络应用时,我们主要在代码中进行这些改进。

但是,你有没有想过将 GPU 的力量结合到你的网络应用中来提高性能?

本文将向你介绍一个名为 GPU.js 的 JavaScript 加速库,并告诉你如何改进复杂的计算。

什么是 GPU.js

首先,官网地址:

https://gpu.rocks/#/

Source: https://gpu.rocks/#/

简而言之,GPU.js 是一个 JavaScript 加速库,可用于使用 JavaScript 在 GPU 上进行通用计算。它支持浏览器、Node.js 和 TypeScript。

除了性能提升外,我推荐使用 GPU.js 的原因还有以下几点:

  • GPU.js 使用 JavaScript 作为基础,允许你使用 JavaScript 语法。
  • 它承担着将 JavaScript 自动转译为着色器语言的责任,并对它们进行编译。
  • 如果设备中没有 GPU,它可以退回到普通的 JavaScript 引擎。因此,使用 GPU.js 不会有任何不利因素。
  • GPU.js 也可以用于并行计算。此外,你可以同时在 CPU 和 GPU 上异步地进行多项计算。

所有这些东西加在一起,我不认为有理由不使用 GPU.js。因此,让我们看看如何开始使用它。

如何设置 GPU.js?

为您的项目安装 GPU.js 与其他的 JavaScript 库类似。

对于 Node 项目

  1. npm install gpu.js --save 
  2. or 
  3. yarn add gpu.js 
  4. import { GPU } from ('gpu.js'
  5. --- or --- 
  6. const { GPU } = require('gpu.js'
  7. --- or --- 
  8. import { GPU } from 'gpu.js'; // Use this for TypeScript 
  9. const gpu = new GPU(); 

对于 Bowsers

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

  1. <script src="dist/gpu-browser.min.js"></script> 
  2. --- or --- 
  3. <script 
  4.   src="https://unpkg.com/gpu.js@latest/dist/gpu- browser.min.js"
  5. </script> 
  6. <script 
  7.   rc="https://cdn.jsdelivr.net/npm/gpu.js@latest/dist/gpu-browser.min.js"
  8. </script> 
  9. <script> 
  10.  const gpu = new GPU(); 
  11.  ... 
  12. </script> 

 

 

注意:

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

这就是你需要知道的关于安装和导入 GPU.js 的情况。

现在,你可以开始在你的应用程序中使用 GPU 编程。

此外,我强烈建议理解 GPU.js 的基本功能和概念。所以,让我们从 GPU.js 的一些基础知识开始。

创建函数

你可以在 GPU.js 中定义函数以在 GPU 中运行,使用一般的 JavaScript 语法。

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

上面的代码样本显示了一个 GPU.js 函数的基本结构。我将该函数命名为 exampleKernel。正如你所看到的,我使用了 createKernel 函数,利用 GPU 进行计算。

另外,定义输出的大小是必须的。在上面的例子中,我使用了一个名为 settings 的参数来指定输出大小。

  1. const settings = { 
  2.     output: [100] 
  3. }; 

内核函数的输出可以是 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 函数中使用任何整数或浮点数。

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

Boolean

GPU.js 中也支持布尔值,与 JavaScript 类似。

  1. const kernel = gpu.createKernel(function() { 
  2.   const bool = true
  3.   if (bool) { 
  4.     return 1; 
  5.   }else
  6.     return 0; 
  7.   } 
  8. },settings); 

Arrays

你可以在内核函数中定义任何大小的数字数组,并返回它们。

  1. const exampleKernel = gpu.createKernel(function() { 
  2.  const array1 = [0.01, 1, 0.1, 10]; 
  3.  return array1; 
  4. }, settings); 

Functions

在内核函数中使用私有函数,在 GPU.js 中也是允许的。

  1. const exampleKernel = gpu.createKernel(function() { 
  2.   function privateFunction() { 
  3.     return [0.01, 1, 0.1, 10]; 
  4.   } 
  5.   return privateFunction(); 
  6. }, settings); 

支持的输入类型

除了上述变量类型外,你还可以向内核函数传递几种输入类型。

Numbers

与变量声明类似,你可以向内核函数传递整数或浮点数,如下所示。

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

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

你可以将 Array、Float32Array、Int16Array、Int8Array、Uint16Array、uInt8Array 等数组类型传入 GPU.js 内核。

  1. const exampleKernel = gpu.createKernel(function(x) { 
  2.  return x; 
  3. }, settings); 
  4. exampleKernel([1, 2, 3]); 

预扁平化的 2D 和 3D 数组也被内核函数所接受。这种方法使上传的速度更快,你必须使用 GPU.js 的输入选项来实现这一点。

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

HTML Images

与传统的 JavaScript 相比,将图像传递到函数中是我们在 GPU.js 中可以看到的一个新东西。使用 GPU.js,你可以将一个或多个 HTML 图像作为数组传递给内核函数。

  1. //Single Image 
  2. const kernel = gpu.createKernel(function(image) { 
  3.     ... 
  4. }) 
  5.   .setGraphical(true
  6.   .setOutput([100, 100]); 
  7.  
  8. const image = document.createElement('img'); 
  9. image.src = 'image1.png'
  10. image.onload = () => { 
  11.   kernel(image); 
  12.   document.getElementsByTagName('body')[0].appendChild(kernel.canvas); 
  13. }; 
  14. //Multiple Images 
  15. const kernel = gpu.createKernel(function(image) { 
  16.     const pixel = image[this.thread.z][this.thread.y][this.thread.x]; 
  17.     this.color(pixel[0], pixel[1], pixel[2], pixel[3]); 
  18. }) 
  19.   .setGraphical(true
  20.   .setOutput([100, 100]); 
  21.  
  22. const image1 = document.createElement('img'); 
  23. image1.src = 'image1.png'
  24. image1.onload = onload; 
  25. .... 
  26. //add another 2 images 
  27. .... 
  28. const totalImages = 3; 
  29. let loadedImages = 0; 
  30. function onload() { 
  31.   loadedImages++; 
  32.   if (loadedImages === totalImages) { 
  33.     kernel([image1, image2, image3]); 
  34.      document.getElementsByTagName('body')[0].appendChild(kernel.canvas); 
  35.   } 
  36. }; 

除了上述配置外,还有许多令人兴奋的事情可以用 GPU.js 进行实验。你可以在其文档中找到它们。既然你现在了解了几种配置,让我们用 GPU.js 写一个函数并比较其性能。

使用 GPU.js 的第一个功能

通过结合我们之前讨论的所有内容,我写了一个小型的 angular 应用程序,通过将两个有 1000 个元素的数组相乘来比较 GPU 和 CPU 的计算性能。

第 1 步,生成 1000 个元素的数组的函数

我将生成一个每个元素有 1000 个数字的 2D 数组,并在接下来的步骤中使用它们进行计算。

  1. generateMatrices() { 
  2.  this.matrices = [[], []]; 
  3.  for (let y = 0; y < this.matrixSize; y++) { 
  4.   this.matrices[0].push([]) 
  5.   this.matrices[1].push([]) 
  6.   for (let x = 0; x < this.matrixSize; x++) { 
  7.    const value1 = parseInt((Math.random() * 10).toString()) 
  8.    const value2 = parseInt((Math.random() * 10).toString()) 
  9.    this.matrices[0][y].push(value1) 
  10.    this.matrices[1][y].push(value2) 
  11.   } 
  12.  } 

第 2 步,内核函数

这是这个应用程序中最关键的函数,因为所有的 GPU 计算都发生在这里。

在这里,multiplyMatrix 函数将接收两个数字数组和矩阵的大小作为输入。

然后,它将把两个数组相乘并返回总和,同时使用性能 API 测量时间。

  1. gpuMultiplyMatrix() { 
  2.   const gpu = new GPU(); 
  3.   const multiplyMatrix = gpu.createKernel(function (a: number[][], b: number[][], matrixSize: number) { 
  4.    let sum = 0; 
  5.  
  6.    for (let i = 0; i < matrixSize; i++) { 
  7.     sum += a[this.thread.y][i] * b[i][this.thread.x]; 
  8.    } 
  9.    return sum
  10.   }).setOutput([this.matrixSize, this.matrixSize]) 
  11.   const startTime = performance.now(); 
  12.   const resultMatrix = multiplyMatrix(this.matrices[0],  this.matrices[1], this.matrixSize); 
  13.  
  14.   const endTime = performance.now(); 
  15.   this.gpuTime = (endTime - startTime) + " ms"
  16.  
  17.   console.log("GPU TIME : "+ this.gpuTime); 
  18.   this.gpuProduct = resultMatrix as number[][]; 

步骤 3,CPU 乘法函数。

这是一个传统的 TypeScript 函数,用于测量相同数组的计算时间。

  1. cpuMutiplyMatrix() { 
  2.   const startTime = performance.now(); 
  3.   const a = this.matrices[0]; 
  4.   const b = this.matrices[1]; 
  5.   let productRow = Array.apply(null, new Array(this.matrixSize)).map(Number.prototype.valueOf, 0); 
  6.   let product = new Array(this.matrixSize); 
  7.  
  8.   for (let p = 0; p < this.matrixSize; p++) { 
  9.     product[p] = productRow.slice(); 
  10.   } 
  11.  
  12.   for (let i = 0; i < this.matrixSize; i++) { 
  13.     for (let j = 0; j < this.matrixSize; j++) { 
  14.       for (let k = 0; k < this.matrixSize; k++) { 
  15.         product[i][j] += a[i][k] * b[k][j]; 
  16.       } 
  17.     } 
  18.   } 
  19.   const endTime = performance.now(); 
  20.   this.cpuTime = (endTime — startTime) + “ ms”; 
  21.   console.log(“CPU TIME : “+ this.cpuTime); 
  22.   this.cpuProduct = product; 

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 是赢家。

结论

根据我使用 GPU.js 的实验,它可以提高 JavaScript 应用程序的性能。

 

但是,我们必须注意只将 GPU 用于复杂的任务。否则,我们将浪费资源,最终会降低应用程序的性能,如上图所示。不过,如果你还没有尝试过 GPU.js,我邀请大家使用它。

 

责任编辑:武晓燕 来源: TianTianUp
相关推荐

2020-12-01 06:53:37

GPUJavaScript

2017-12-14 14:32:30

.Net内存代码

2009-02-09 18:02:00

2015-03-31 14:47:22

JavaJava性能

2011-07-27 14:10:43

javascript

2020-03-18 10:04:34

存储机器学习服务器

2012-06-01 09:54:03

2012-03-09 09:51:35

2020-05-06 07:32:05

物联网IOT企业

2015-04-22 14:41:04

云迁移Redis缓存数据模型调整

2013-06-18 10:30:42

虚拟化存储虚拟化

2020-07-15 07:53:41

VSCode Task脚本命令

2020-10-19 08:00:00

PowerToysWindows 10Windows

2010-08-03 10:04:51

Linux Kerne

2014-08-14 10:04:19

OpenStackDHCP

2011-04-20 10:51:56

网络流量分析工具网络监测

2009-06-10 22:00:57

JavaScript脚

2009-06-11 17:15:23

JavaScript性

2010-06-10 12:47:01

UML2.0

2024-02-26 00:02:00

开发Go
点赞
收藏

51CTO技术栈公众号