10

When using kernel objects to synchronize threads running on different CPUs, is there perhaps some extra runtime cost when using Windows Server 2008 R2 relative to other OS's?

Edit: And as found out via the answer, the question should also include the phrase, "when running at lower CPU utilization levels." I included more information in my own answer to this question.

Background

I work on a product that uses shared memory and semaphores for communication between processes (when the two processes are running on the same machine). Reports of performance problems on Windows Server 2008 R2 (which I shorten to Win2008R2 after this) led me to find that sharing a semaphore between two threads on Win2008R2 was relatively slow compared to other OS’s.

Reproducing it

I was able to reproduce it by running the following bit of code concurrently on two threads:

for ( i = 0; i < N; i++ )
  {
  WaitForSingleObject( globalSem, INFINITE );
  ReleaseSemaphore( globalSem, 1, NULL );
  }

Testing with a machine that would dual boot into Windows Server 2003 R2 SP2 and Windows Server 2008 R2, the above snippet would run about 7 times faster on the Win2003R2 machine versus the Win2008R2 (3 seconds for Win2003R2 and 21 seconds for Win2008R2).

Simple Version of the Test

The following is the full version of the aforementioned test:

#include <windows.h>
#include <stdio.h>
#include <time.h>


HANDLE gSema4;
int    gIterations = 1000000;

DWORD WINAPI testthread( LPVOID tn )
{
   int count = gIterations;

   while ( count-- )
      {
      WaitForSingleObject( gSema4, INFINITE );
      ReleaseSemaphore( gSema4, 1, NULL );
      }

   return 0;
}


int main( int argc, char* argv[] )
{
   DWORD    threadId;
   clock_t  ct;
   HANDLE   threads[2];

   gSema4 = CreateSemaphore( NULL, 1, 1, NULL );

   ct = clock();
   threads[0] = CreateThread( NULL, 0, testthread, NULL, 0, &threadId );
   threads[1] = CreateThread( NULL, 0, testthread, NULL, 0, &threadId );

   WaitForMultipleObjects( 2, threads, TRUE, INFINITE );

   printf( "Total time = %d\n", clock() - ct );

   CloseHandle( gSema4 );
   return 0;
}

More Details

I updated the test to enforce the threads to run a single iteration and force a switch to the next thread at each loop. Each thread signals the next thread to run at the end of each loop (round-robin style). And I also updated it to use a spinlock as an alternative to the semaphore (which is a kernel object).

All machines I tested on were 64-bit machines. I compiled the test mostly as 32-bit. If built as 64-bit, it ran a bit faster overall and changed the ratios some, but the final result was the same. In addition to Win2008R2, I also ran against Windows 7 Enterprise SP 1, Windows Server 2003 R2 Standard SP 2, Windows Server 2008 (not R2), and Windows Server 2012 Standard.

  • Running the test on a single CPU was significantly faster (“forced” by setting thread affinity with SetThreadAffinityMask and checked with GetCurrentProcessorNumber). Not surprisingly, it was faster on all OS’s when using a single CPU, but the ratio between multi-cpu and single cpu with the kernel object synchronization was much higher on Win2008R2. The typical ratio for all machines except Win2008R2 was 2x to 4x (running on multiple CPUs took 2 to 4 times longer). But on Win2008R2, the ratio was 9x.
  • However ... I was not able to reproduce the slowdown on all Win2008R2 machines. I tested on 4, and it showed up on 3 of them. So I cannot help but wonder if there is some kind of configuration setting or performance tuning option that might affect this. I have read performance tuning guides, looked through various settings, and changed various settings (e.g., background service vs foreground app) with no difference in behavior.
  • It does not seem to be necessarily tied to switching between physical cores. I originally suspected that it was somehow tied to the cost of accessing global data on different cores repeatedly. But when running a version of the test that uses a simple spinlock for synchronization (not a kernel object), running the individual threads on different CPUs was reasonably fast on all OS types. The ratio of the multi-cpu semaphore sync test vs multi-cpu spinlock test was typically 10x to 15x. But for the Win2008R2 Standard Edition machines, the ratio was 30x.

Here are some actual numbers from the updated test (times are in milliseconds):

+----------------+-----------+---------------+----------------+
|       OS       | 2 cpu sem |   1 cpu sem   | 2 cpu spinlock |
+----------------+-----------+---------------+----------------+
| Windows 7      | 7115 ms   | 1960 ms (3.6) | 504 ms (14.1)  |
| Server 2008 R2 | 20640 ms  | 2263 ms (9.1) | 866 ms (23.8)  |
| Server 2003    | 3570 ms   | 1766 ms (2.0) | 452 ms (7.9)   |
+----------------+-----------+---------------+----------------+

Each of the 2 threads in the test ran 1 million iterations. Those testes were all run on identical machines. The Win Server 2008 and Server 2003 numbers are from a dual boot machine. The Win 7 machine has the exact same specs but was a different physical machine. The machine in this case is a Lenovo T420 laptop with Core i5-2520M 2.5GHz. Obviously not a server class machine, but I get similar result on true server class hardware. The numbers in parentheses are the ratio of the first column to the given column.

Any explanation for why this one OS would seem to introduce extra expense for kernel level synchronization across CPUs? Or do you know of some configuration/tuning parameter that might affect this?

While it would make this exceedingly verbose and long post longer, I could post the enhanced version of the test code that the above numbers came from if anyone wants it. That would show the enforcement of the round-robin logic and the spinlock version of the test.

Extended Background

To try to answer some of the inevitable questions about why things are done this way. And I'm the same ... when I read a post, I often wonder why I am even asking. So here are some attempts clarify:

  • What is the application? It is a database server. In some situations, customers run the client application on the same machine as the server. In that case, it is faster to use shared memory for communications (versus sockets). This question is related to the shared memory comm.
  • Is the workload really that dependent on events? Well ... the shared memory comm is implemented using named semaphores. The client signals a semaphore, the server reads the data, the server signals a semaphore for the client when the response is ready. In other platforms, it is blinding fast. On Win2008R2, it is not. It is also very dependent on the customer application. If they write it with lots of small requests to the server, then there is a lot of communication between the two processes.
  • Can a lightweight lock be used? Possibly. I am already looking at that. But it is independent of the original question.
15
  • Try running perfview or xperf. Look at the kernel call stacks. Maybe they contain a clue.; Anyway, I would be careful to generalize from this contrived workload to a real-world workload. On Win7 the dispatcher lock was broken increasing scalability. But it might have hurt these contrived benchmarks.
    – usr
    Jan 18, 2013 at 18:37
  • xperf/WPA is a good idea. I will try that out. I am not familiar with perfview ... is it useful for native apps? A brief look seems like it is .NET oriented. I agree about generalizing a very simple test to the real world. But in this case I am fairly sure it is the same thing. I worked backwards in the real world app to this simple example. In fact, if I restricted the real world applications to run on a single CPU, it was blazing fast (several times faster on Win2008R2). Jan 18, 2013 at 18:50
  • perfview is for native. I'm not familiar with xperf so I recommended something that I could support. By all means, use xperf.; Is your workload really that dependent on events? Could you switch to lightweight locks? What are you doing that you depend on waiting that much?
    – usr
    Jan 18, 2013 at 19:00
  • 1
    Also, you should wait for your threads with WaitForMultipleObjects instead of sleep. Jan 18, 2013 at 19:13
  • 1
    @usr: The power plan setting is a very good call. Windows 2008 R2 does indeed have a default of "balanced". I changed that to High performance and it did speed it up. So I started poking around more and looked at BIOS settings. There was a CPU Power Management option in the BIOS that I changed to Disabled, and then Win2008R2 was nearly as fast as Win 2003 on the dual boot machine. So it seems that Windows 2008 R2 is much more affected by (or obeys) various power settings over other OS's. If you add this information as an answer I will upvote it and select it as the answer. Jan 21, 2013 at 23:36

4 Answers 4

3

Pulled from the comments into an answer:

Maybe the server is not set to the high-performance power plan? Win2k8 might have a different default. Many servers aren't by default, and this hits performance very hard.

The OP confirmed this as the root cause.

This is a funny cause for this behavior. The idea flashed up in my head while I was doing something completely different.

1
  • There are still a few unanswered questions and I have opened an issue on my MSDN subscription to try to get that figured out. And I'm also not sure this is the customer's reported issue ... but at this point I'm betting it is. So thanks for pointing me in the right direction! Jan 21, 2013 at 23:50
0

It could well be the OS installation configuration varies. Perhaps the slow system is configured to disallow multiple threads from your process being scheduled simultaneously. If some other high priority process were always (or mostly) ready to run, the only alternative is for your threads to be run sequentially, not in parallel.

2
  • When I tested, I made sure nothing else was running (the CPUs were all essentially idle). And I also verified that the threads were indeed running on multiple cores (via task manager, and coded calls to GetCurrentProcessorNumber). And, ironically, when they are forced to be serialized on one CPU, it is faster (that is the second column of numbers in the table in the OP). Jan 18, 2013 at 17:56
  • I want to explain my downvote: I feel this answer does not get us even near an explanation. If the OS is misconfigured, what would be the relevant knobs to look at? The Windows thread scheduler has almost no knobs.
    – usr
    Jan 18, 2013 at 18:36
0

I'm adding this additional "answer" information here rather than burying it in my overly long OP. @usr pointed me in the right direction with the power management options suggestion. The contrived test in the OP as well as the original problem involves a lot of handshaking between different threads. The handshaking in the real world app was across different processes, but testing showed the results do not differ if it is threads or processes doing the handshaking. The sharing of the semaphore (kernel sync object) across the CPUs seems to be greatly affected in Windows Server 2008 R2 by the power settings when running at low (e.g., 5% to 10%) CPU usage. My understanding of this at this point is purely based on measuring and timing applications.

A related question on Serverfault talks about this some as well.

The Test Settings

OS Power Options Setting The default power plan for Windows Server 2008 R2 is "Balanced". Changing it to the "High Performance" option helped performance of this test quite a bit. In particular, one specified setting under the "Change advanced power settings" seems to be the critical one. The advanced settings has an option under Processor power management called Minimum processor state. The default value for this under the Balanced plan seems to be 5%. Changing that to 100% in my testing was the key.

BIOS Setting In addition, a BIOS setting affected this test greatly. I'm sure this varies a lot across hardware, but the primary machine I tested on has a setting named "CPU Power Management". The description of the BIOS setting is, "Enables or disables the power saving feature that stop (sic) the microprocessor clock automatically when there are no system activities." I changed this option to "Disabled".

Empirical Results

The two test cases shown are:

  • (a) Simple. A modified version of the one included in the OP. This simple test enforced round-robin switching at every iteration between two threads on two CPUs. Each thread ran 1 million iterations (thus, there were 2 million context switches across CPUs).
  • (b) Real World. The real world client/server test where a client was making many "small" requests of the server via shared memory and synchronized with global named semaphores.

The three test scenarios are:

  • (i) Balanced. Default installation of Windows Server 2008 R2, which uses the Balanced power plan.
  • (ii) HighPerf. I changed the power option from "Balanced" to "High Performance". Equivalently, the same results occurred by setting the Minimum Processor State CPU option as described above to 100% (from 5%).
  • (iii) BIOS. I disabled the CPU Power Management BIOS option as described above and also left the High Performance power option selected.

The times given are in seconds:

╔════════════════╦═════════════╦═══════════════╦════════════╗
║                ║ (i)Balanced ║ (ii) HighPerf ║ (iii) BIOS ║
╠════════════════╬═════════════╬═══════════════╬════════════╣
║ (a) Simple     ║ 21.4 s      ║ 9.2 s         ║ 4.0 s      ║
║ (b) Real World ║ 9.3 s       ║ 2.2 s         ║ 1.7 s      ║
╚════════════════╩═════════════╩═══════════════╩════════════╝

So after both changes were made (OS and BIOS), both the real world test and the contrived test ran about 5 times faster than under the default installation and default BIOS settings.


While I was testing these cases, I sometimes encountered a result I could not explain. When the CPU was busy (some background process would fire up), the test would run faster. I would file it away in my head and be puzzled for a while. But now it makes sense. When another process would run, it would bump up the CPU usage past whatever threshold was needed to keep it in a high power state and the context switches would be fast. I still do not know what aspect is slow (the primary cost is buried in the WaitForSingleObject call) but the end results now all kind of make sense.

-3

This isn't a reasonable benchmark, your semaphores are always frobbed in the same process (and so presumably on the same CPU/core). An important part of the cost of locking in real-world cases is the memory accesses involved when different CPUs/cores fight over exclusive access to the memory area (which bounces back and forth between caches). Look for some more real-world benchmarks (sorry, not my area), o (even better) measure (some cut down version of) your application with (contrived, but realistic) test data.

[Test data for benchmarks should never be the ones for testing or regression testing: the later pokes at (probably rarely used) corner cases, you want "typical" runs for benchmarking.]

1
  • No they do not run on the same CPU. I verified via task manager, API calls, and other means that they run on multiple CPUs. Windows is good at scheduling threads to utilize multiple cores. The presumption that threads in the same process run on the same CPU is incorrect. Also ... I'm unsure how the rest of your answer applies. The question is why the code runs relatively slowly on Win2008R2 versus other OS versions. Can you perhaps elaborate and correct? Jan 21, 2013 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.