Java中人工生成cpu负载

发布于 2024-11-12 01:31:30 字数 60 浏览 3 评论 0原文

有没有一种简单的方法可以在 Java 中生成恒定的 CPU 负载?就像生成 60% 的 CPU 负载一样。

Is there a simple way to generate a constant CPU load in Java? Like generate CPU load at 60%.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏花。依旧 2024-11-19 01:31:30

有点晚了,但只是想分享我创建了一个名为 FakeLoad 可用于动态生成不同类型的系统负载,如 CPU、内存和磁盘 I/O。

例如,使用 FakeLoad 生成 60% 的 CPU 负载 30 秒,可以这样完成:

// Creation
FakeLoad fakeload = FakeLoads.create()
    .lasting(30, TimeUnit.SECONDS)
    .withCpu(60);

// Execution
FakeLoadExecutor executor = FakeLoadExecutors.newDefaultExecutor(); 
executor.execute(fakeload);

它不能提供完美的精度,但它能够生成相当恒定且准确的负载。它可以在 Maven Central 上找到,所以请随意尝试一下:)

Kind of late to the party, but just wanted to share that I created a small open-source client library called FakeLoad which can be used to generate different kinds of system load like CPU, memory, and disk I/O on the fly.

For instance, generating a CPU load of 60% for 30 seconds with FakeLoad can be done like this:

// Creation
FakeLoad fakeload = FakeLoads.create()
    .lasting(30, TimeUnit.SECONDS)
    .withCpu(60);

// Execution
FakeLoadExecutor executor = FakeLoadExecutors.newDefaultExecutor(); 
executor.execute(fakeload);

It doesn't provide perfect precision, but it is able to generate quite constant and accurate loads. It is available on Maven Central, so feel free to give it a try :)

只有一腔孤勇 2024-11-19 01:31:30

尚未对此进行测试,但它可能大致有效,以使您的应用程序以正确的比例工作和睡眠。像(伪代码)这样​​的东西:

load = 60;  
do forever
  time = current_system_time_ms() + load
  while (current_system_time_ms() < time)
     // just consume some time for 60 ms 
  end

  SLEEP(100 - load);  // sleep for 40 ms
end 

好的,你要求一个简单的方法,但是......:)

Have not tested this, but it might roughly work, to make your application work and sleep in the correct ratio. Something like (pseudocode):

load = 60;  
do forever
  time = current_system_time_ms() + load
  while (current_system_time_ms() < time)
     // just consume some time for 60 ms 
  end

  SLEEP(100 - load);  // sleep for 40 ms
end 

Ok, you asked for a simple way, but ... :)

陪你到最终 2024-11-19 01:31:30

我认为这甚至是不可能的,因为:

  1. JVM 解释代码的方式(假设它完全解释代码)是依赖于实现的
  2. 编译器,并且 JVM 可以优化代码(当然以依赖于实现的方式),以便您可以运行与给定 .class 文件中的字节码不同的字节码。

I think that's not even possible, because:

  1. the way the JVM interprets code (provided it interprets code at all) is implementation-dependent
  2. the compiler, and the JVM, may optimize code (in an implementation-dependent manner, of course) so that you may run different bytecodes than the ones in a given .class file.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文