如何让循环停止

时间:2015-02-02 00:25:46

标签: java multithreading performance

我需要帮助或一些关于如何在此代码中获取循环以在speedUp因子稳定到特定值时停止执行的想法。这种方法的想法是不断运行越来越多的线程,并从结果中获得speedUp因子。舍入的speedUp因子是机器上存在的核心数。运行4线程任务将具有与4核机器上的16线程任务相同的speedUp因子。我希望能够不必手动设置要运行的线程数。当speedUp因子稳定到一个值时,我希望程序终止。如果加速因子已经设置为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);
	}
}

1 个答案:

答案 0 :(得分:2)

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

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

作为旁注,如果您想要核心数,可以致电:

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