java - 如何让循环停止

标签 java multithreading performance

我需要帮助或一些关于如何在加速因子达到特定值时停止执行此代码中的循环的想法。此方法的想法是不断运行数量不断增加的线程,并从结果中得出加速因子。舍入加速因子是机器上存在的核心数量。在 4 核计算机上运行 4 线程任务将具有与 16 线程任务相同的加速因子。我希望不必手动设置要运行的线程数。当加速因子达到某个值时,我希望程序终止。例如,如果加速因子已经稳定在 2,则无需运行 8、16 或 32 个线程的测试。

4 核机器的输出示例:

测试的线程数:1 加速系数:1.0

测试的线程数:2 加速系数:1.8473736372646188

测试的线程数:4 加速系数:3.9416666666666669

测试的线程数:8 加速系数:3.9750993377483446

测试的线程数:16 加速系数:4.026086956521739

这台机器有:4 个核心

应用程序已完成执行。谢谢您

private static void multiCoreTest() {
		// A runnable for the threads
		Counter task = new Counter(1500000000L);
		
		// A variable to store the number of threads to run
		int threadMultiplier = 1;
		
		// A variable to hold the time it takes for a single thread to execute
		double singleThreadTime = ThreadTest.runTime(1, task);

		// Calculating speedup factor for a single thread task
		double speedUp = (singleThreadTime * threadMultiplier) / (singleThreadTime);
	
		// Printing the speed up factor of a single thread
		System.out.println("Number of threads tested: " + threadMultiplier);
		System.out.println("Speed up factor: " + speedUp);

		// Testing multiple threads
		while (threadMultiplier < 16) {

			// Increasing the number of threads by a factor of two
			threadMultiplier *= 2;

			// A variable to hold the time it takes for multiple threads to
			// execute
			double multiThreadTime = ThreadTest.runTime(threadMultiplier, task);

			// Calculating speedup factor for multiple thread tests
			speedUp = (singleThreadTime * threadMultiplier) / (multiThreadTime);

			// Message to the user
			System.out.println("\n" + "Number of threads tested: "
					+ threadMultiplier);
			System.out.println("Speed up factor: " + speedUp);

		}
		// Print number of cores
		System.out.println("\n" + "THIS MACHINE HAS: " + Math.round(speedUp)
				+ " CORES");
		System.out.println("\n"
				+ "THE APPLICATION HAS COMPLETED EXECUTION. THANK YOU");
		// Exiting the system
		System.exit(0);
	}
}

最佳答案

测试新的加速比是否与旧的相同:

double oldSpeedUp = 0;
boolean found = false;
while(!found && threadMultiplier < 16) {
    // ...
    found = Math.round(speedUp) == Math.round(oldSpeedUp);
    oldSpeedUp = speedUp;
}

顺便说一句,如果您想要核心数量,可以调用:

int cores = Runtime.getRuntime().availableProcessors();

关于java - 如何让循环停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28269555/

相关文章:

php - Apache 工作台 : Why so many 503s?

c++ - 如何将指向类方法的指针传递给 boost 线程

multithreading - COM 线程模型 - 永久的困惑

multithreading - POSIX线程参数

performance - iis7增加每个工作进程的线程/并发请求数

java - 学习构造函数 - 无输出

java - Maven war 插件问题

java - 这个错误代码是什么意思(附代码)

java - 如何在同一行打印 2 个 for 循环的结果

xml - 使用 Hadoop 处理 xml 文件