高效计算MD5校验和
我正在使用以下代码来获取文件的校验和。它在计算过程中使用 50% 的 CPU。
MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = new FileInputStream("C:\\Temp\\Small\\Movie.mp4"); // Size 700 MB
byte [] buffer = new byte [blockSize];
int numRead;
do
{
numRead = is.read(buffer);
if (numRead > 0)
{
md.update(buffer, 0, numRead);
}
} while (numRead != -1);
byte[] digest = md.digest();
可以采取哪些措施来减少代码使用最大 CPU 的
除了 Thread.sleep(ms) 之外, 情况, 金斯利·鲁本·J
I'm using following code to get the Checksum of a file. It uses 50% of CPU during calculations.
MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = new FileInputStream("C:\\Temp\\Small\\Movie.mp4"); // Size 700 MB
byte [] buffer = new byte [blockSize];
int numRead;
do
{
numRead = is.read(buffer);
if (numRead > 0)
{
md.update(buffer, 0, numRead);
}
} while (numRead != -1);
byte[] digest = md.digest();
What can be done to reduce the code from using maximum CPU other than Thread.sleep(ms)
regards,
Kingsley Reuben J
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 < code>Thread.setPriority(int newPriority)方法降低线程的优先级。这将导致其他更高优先级的线程更频繁地执行。然而,如果您不考虑优先级,您的 MD5 的计算速度不会那么快 - 为什么您不希望此计算尽快完成呢?
编辑:这是一个“Fast MD5”实现,与 Java 的默认
java.security.MessageDigest
实现相比,性能显着提高(平均快 26%)。有关详细信息,请参阅作者页面,包括代码示例和基准。该代码可在 GNU LGPL 2.1 许可证下获取。You could use the
Thread.setPriority(int newPriority)
method to reduce the thread's priority. This will result in other higher-priority threads being executed more often. However, your MD5 will not be calculated as quickly as if you left the priority alone -- why wouldn't you want this calculation to complete as quickly as possible?EDIT: Here is a "Fast MD5" implementation, which boasts a significant performance increase (26% faster on average) over Java's default
java.security.MessageDigest
implementation. See the author's page for detailed information, including code examples and benchmarks. The code is available under the GNU LGPL 2.1 license.我宁愿将优先级管理专门用于操作系统,对于 Windows,您可以使用它来启动您的应用程序
I'd rather dedicate priority management to os, for windows you could start your app with