简体   繁体   English

std::lock_guard 如何比 std::mutex::lock() 更快?

[英]How can std::lock_guard be faster than std::mutex::lock()?

I was arguing with a colleague, about lock_guard, and he proposed that lock_guard is problably slower than mutex::lock() / mutex::unlock() due to the cost of instantiate and unistantiate the class lock_guard.我和一位同事争论 lock_guard,他提出 lock_guard 可能比 mutex::lock() / mutex::unlock() 慢,原因是实例化和非实例化类 lock_guard 的成本。

Then I created this simple test and, surprisely, the version with lock_guard is almost two times faster than the version with mutex::lock() / mutex::unlock()然后我创建了这个简单的测试,令人惊讶的是,带有 lock_guard 的版本几乎比带有 mutex::lock() / mutex::unlock() 的版本快两倍

#include <iostream>
#include <mutex>
#include <chrono>

std::mutex m;
int g = 0;

void func1()
{
    m.lock();
    g++;
    m.unlock();
}

void func2()
{
    std::lock_guard<std::mutex> lock(m);
    g++;
}

int main()
{
    auto t = std::chrono::system_clock::now();
    for (int i = 0; i < 1000000; i++)
    {
        func1();
    }

    std::cout << "Take: " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - t).count() << " ms" << std::endl;

    t = std::chrono::system_clock::now();
    for (int i = 0; i < 1000000; i++)
    {
        func2();
    }

    std::cout << "Take: " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - t).count() << " ms" << std::endl;

    return 0;
}

The results on my machine:我机器上的结果:

Take: 41 ms
Take: 22 ms

Can someone clarify why and how this can be?有人可以澄清为什么以及如何做到这一点吗?

The release build produces the same result for both versions.发布版本对两个版本产生相同的结果。

The DEBUG build shows ~33% longer time for func2 ; DEBUG构建显示func2时间延长了约 33%; the difference I see in the disassembly that func2 uses __security_cookie and invokes @_RTC_CheckStackVars@8 .我在反汇编中看到的区别是func2使用__security_cookie并调用@_RTC_CheckStackVars@8

Are you timing DEBUG?你在定时调试吗?

EDIT: Additionally, while looking at RELEASE disassembly, I noticed that mutex methods were saved in two registries:编辑:此外,在查看RELEASE反汇编时,我注意到mutex方法保存在两个注册表中:

010F104E  mov         edi,dword ptr [__imp___Mtx_lock (010F3060h)]  
010F1054  xor         esi,esi  
010F1056  mov         ebx,dword ptr [__imp___Mtx_unlock (010F3054h)]  

and called the same way from both func1 and func2 :并从func1func2以相同的方式func2

010F1067  call        edi  
....
010F107F  call        ebx  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM