In this code sample I benchmark scoped vs manual locking of a pthread mutex. I expected equal perfomance for both approaches. But much to my surprise the scoped lock solution seems a little faster.
Can anyone explain why this happens?
I’m using using g++ 4.5.2 and compile with the following options:
g++ -std=c++0x -O2 -o test main.cpp
Update
When doing 2 billion iterations on my local PC (not Ideone) I get a larger difference:
g++ -std=c++0x -O2 -o test main.cpp
scoped_lock: 10530ms
normal: 11290ms
scoped_lock: 10530ms
normal: 11280ms
scoped_lock: 10530ms
normal: 11280ms
scoped_lock: 10530ms
normal: 11290ms
Update 2
I improved the program with a higher resolution clock: http://ideone.com/CMbuw. This time the scoped lock is a little slower.
I think it’s safe to conclude that it’s a measuring anomaly.
I changed the iteration count to 50 millions (was 20 millions in your code) and the results are now
perfectly identical. So I’d blame measurement errors in your test case – just not enough iterations of code. If you really care you should look into emitted machine code.