gpt4 book ai didi

java - 为什么 ThreadMXBean.getThreadCpuTime 返回相同的时间?

转载 作者:行者123 更新时间:2023-12-01 16:30:18 25 4
gpt4 key购买 nike

我尝试使用ThreadMXBean.getThreadCpuTime来获取主线程的CPU时间。然而,尽管线程必须完成一些需要时间的工作,但我得到了相同的时间。现在,我怀疑使用 ThreadMXBean.getThreadCpuTime 获取 CPU 时间的准确性。我的示例代码如下,

package edu.seu.juc.problem;

import java.lang.management.ManagementFactory;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestGetThreadCpuTime {
private static Lock lock = new ReentrantLock();
/***
*
* @param args
*/
public static void main(String[] args) {

System.out.println("CPU time: " + ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId())
/ (1000 * 1000));

for (int i = 0; i < 8; i++) {
lock.lock();


Long startTime = System.currentTimeMillis();


try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}

Integer sum = 1;
for (int j = 0; j < 1000000; j++) {
sum += j;
}
System.out.println(sum);


System.out.println("total: " + (System.currentTimeMillis() - startTime));
System.out.println("CPU time: " + ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId())
/ (1000 * 1000));

System.out.println("blocked time: " + ManagementFactory.getThreadMXBean().getThreadInfo(Thread.currentThread().getId()).getBlockedTime());
System.out.println("waited time: " + ManagementFactory.getThreadMXBean().getThreadInfo(Thread.currentThread().getId()).getWaitedTime());

lock.unlock();
}
}
}

结果如下

CPU time: 140
1783293665
total: 220
CPU time: 140
blocked time: -1
waited time: -1
1783293665
total: 217
CPU time: 156
blocked time: -1
waited time: -1
1783293665
total: 210
CPU time: 171
blocked time: -1
waited time: -1
1783293665
total: 215
CPU time: 187
blocked time: -1
waited time: -1
1783293665
total: 204
CPU time: 187
blocked time: -1
waited time: -1
1783293665
total: 203
CPU time: 187
blocked time: -1
waited time: -1
1783293665
total: 203
CPU time: 187
blocked time: -1
waited time: -1

为什么CPU时间保持187ms?好像不太合理。

最佳答案

您看到的时间基于计算机的操作系统行为以及操作系统执行任务的方式。您现在看到的是 187 毫秒,但是如果您重新启动计算机或在其他时间运行此代码,那么您将不会看到一致的 187 毫秒时间。我运行了你的代码,结果如下:

  main CPU time: 143
1783293665
total: 230
main CPU time: 169
blocked time: -1
waited time: -1
1783293665
total: 235
main CPU time: 195
blocked time: -1
waited time: -1
1783293665
total: 215
main CPU time: 208
blocked time: -1
waited time: -1
1783293665
total: 218
main CPU time: 220
blocked time: -1
waited time: -1
1783293665
total: 207
main CPU time: 225
blocked time: -1
waited time: -1
1783293665
total: 209
main CPU time: 231
blocked time: -1
waited time: -1
1783293665
total: 209
main CPU time: 238
blocked time: -1
waited time: -1
1783293665
total: 215
main CPU time: 247
blocked time: -1
waited time: -1

关于java - 为什么 ThreadMXBean.getThreadCpuTime 返回相同的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62056535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com