本文介绍了减少Javascript CPU使用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算在本地写一些用于加密javascript文件的代码。对于大文件和大密钥大小,CPU使用率(自然)非常高。在单个脚本设计中,这通常会挂起浏览器,直到任务完成。

I'm planning on writing some code for encrypting files in javascript locally. For large files and large key sizes, the CPU usage (naturally) is pretty high. In a single script design, this often hangs the browser until the task is complete.

为了提高响应速度并允许用户在我想要的同时做其他事情尝试使脚本'友好'到用户的PC。加密过程将以二进制字符串形式读取文件,然后以块的形式加密字符串(类似于1KB /块 - 需要测试)。我想尝试并使用基于HTML5的工作人员使整个事情尽可能增量。类似于:

In order to improve responsiveness and allow users to do other things in the mean time I want to try make the script 'friendlier' to the user's PC. The encryption process will be reading a file as a binary string and then encrypting the string in chunks (something like 1KB/chunk - needs testing). I want to try and user HTML5-based workers to make the whole thing as incremental as possible. Something like:


  1. Spawn worker

  2. 向worker发送二进制数据块

  3. 工人完成加密,传回新块

  4. 工人死亡。

  1. Spawn worker
  2. Send worker a binary data chunk
  3. Worker completes encryption, passes back new chunk
  4. Worker dies.

这可能也有助于多核处理器,让多个工作人员同时活着。

This might also help with multicore processors, by having multiple workers alive at once.

无论如何,是否有人为了降低CPU使用率而故意放慢脚本速度?将工作人员的加密任务拆分为单个操作,并在它们之间引入延迟之类的事情。

Anyway, has anybody looked at deliberately slowing down a script in order to reduce CPU usage? Something like splitting the worker's encryption task into single operations, and introducing a delay between them.

每100ms间隔计时器回调(示例)。

Interval timer callback every 100ms (example).

工人忙吗?

是 - 等待另一个间隔

否 - 开始加密下一个字母

Is worker busy?
Yes - Wait for another interval
No - Start encrypting the next letter

建议/想法?

有没有人有使用工人的经验?如果你通过使主工作人员成为一名工人来加强主要UI的工作,那么响应能力会增加吗?

Does anyone have experience using workers? If you seperate the main UI from intensieve work by making it a worker, does the responsiveness increase?

推荐答案

这不利用任何HTML5,但这是一个每N毫秒调用一个函数的例子,假设你可以确定一个合适的等待时间。基本上,我试图通过向您展示在执行更多处理之前强制停止一段时间来帮助您。

This doesn't utilize anything HTML5, but here's an example for calling a function every N milliseconds, assuming you can determine an appropriate wait time. Basically, I'm trying to help you by showing you a way to enforce stalling some amount of time before doing more processing.

function doSomething(){
   clearTimeout(timeout);
   // do your "expensive" processing
   // ...
   // decide the job is done and return here or else
   // call doSomething again in sleepMS milliseconds
   timeout = setTimeout(doSomething,sleepMS);
}
var timeout;
var sleepMS = 1000;


doSomething();

编辑

改变了最后一行

var timeout = setTimeout(doSomething,1000);

到此

doSomething()

编辑2

在setTimeout调用中将1000更改为sleepMS,duh:)

Changed 1000 to sleepMS in setTimeout call, duh :)

这篇关于减少Javascript CPU使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 06:59