On dual-core processor, program runs quicker if another program is running at the same time!
This is on a dual-core Athlon II, with Windows XP and Java 1.6.0_07. I have a benchmark program that uses several threads to do a calculation, and which takes 10 seconds to run.
For a demonstration, I have another program that does the same calculation without using threads; it is very simple with a loop that calls a method that calls Math.cos(). When this runs, java.exe uses 50% of the CPU and System Idle Process uses 50%; just as I expect. But instead of taking about 20 seconds as I expect, it takes around 30 seconds. The Task Manager shows that the usage of each core is about 50%.
If I open two Command Prompt windows and in each of them I run this second program, then both processes run simultaneously and take only about 19 seconds. The usage of each core is 100%.
It seems that when only one program is running, the scheduler开发者_运维知识库 cannot decide which core to use and a third of the time is wasted on context switching.
My question is: should I expect this to happen, or does this indicate some kind of misconfiguration?
UPDATE
It is true that experiments can reveal strange results. The replies here (and the linked article) were very helpful, because I had been focused on the details and not on the bigger picture.
Since asking the question, I have found that this particular case is related to power management software that reduces the clock speed when the processor is not fully loaded. This penalises programs that do not use multiple threads.
There's a great talk by Joshua Bloch on difficulties with this kind of benchmarks. Here's an article that summarizes it (there's a link for the talk there too): http://java.dzone.com/articles/joshua-bloch-performance
General conclusion: processors and VMs do all kinds of complex and unpredictable optimizations, that affect benchmarks in counterintuitive ways, such as the one that you described. In any particular case, there is really no way to determine what is causing an anomaly, due to the enormous complexity of the system. Only way to improve performance is using experimentation and statistical analysis of benchmark data.
精彩评论