需要 X 时间的 Java 计算

标签 java android math

这只是一个假设性问题,但可能是解决我一直遇到的问题的一种方法。

想象一下,您希望能够根据计算所需的时间而不是答案来为计算函数计时。因此,您不想找出 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/

相关文章:

java - Jetty 的 XML 模式错误

android - onActivityResult 被立即调用

c - 如何简化我的 "equation"以在 3 和 5 之间切换?

math - 欧拉计划 9 理解

java - Spring MVC 在 WAR 和 JAR 文件中使用 jsp 文件

java - 无法通过 JDBC 连接到虚拟机上的 Oracle 11g : Connection reset

android - 华为 map 不加载瓷砖

C# 方法来缩放值?

java - 在静态图像上制作移动矩形的动画 Java SWT

java - 在 x 和 y 方向重复时设置 BitmapDrawable 的偏移量?