这只是一个假设性问题,但可能是解决我一直遇到的问题的一种方法。
想象一下,您希望能够根据计算所需的时间而不是答案来为计算函数计时。因此,您不想找出 a + b 是多少,而是希望在 < x 秒的时间内继续执行一些计算。
看看这个伪代码:
public static void performCalculationsForTime(int seconds)
{
// Get start time
int millisStart = System.currentTimeMillis();
// Perform calculation to find the 1000th digit of PI
// Check if the given amount of seconds have passed since millisStart
// If number of seconds have not passed, redo the 1000th PI digit calculation
// At this point the time has passed, return the function.
}
现在我知道我是一个可怕、卑鄙的人,因为我使用宝贵的 CPU 周期来简单地打发时间,但我想知道的是:
A) 这可能吗?JVM 会开始提示无响应吗?
B) 如果可能,最好尝试执行哪些计算?
更新 - 答案:
根据答案和评论,答案似乎是“是的,这是可能的。但前提是不在 Android 主 UI 线程中完成,因为用户的 GUI 将变得无响应并且将5 秒后抛出 ANR。”
最佳答案
A) Is this possible and would JVM start complaining about non-responsiveness?
这是可能的,如果你在后台运行它,JVM 和 Dalvik 都不会报错。
B) If it is possible, what calculations would be best to try to perform?
如果目标只是在 x 秒内运行任何计算,只需将总和加 1 直到达到要求的时间。在我的脑海中,像这样的东西:
public static void performCalculationsForTime(int seconds)
{
// Get start time
int secondsStart = System.currentTimeMillis()/1000;
int requiredEndTime = millisStart + seconds;
float sum = 0;
while(secondsStart != requiredEndTime) {
sum = sum + 0.1;
secondsStart = System.currentTimeMillis()/1000;
}
}
关于需要 X 时间的 Java 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31366785/