【问题标题】:Approximate time taken by Boost Thread Specific pointer get() methodBoost 线程特定指针 get() 方法所花费的大约时间
【发布时间】:2013-11-01 11:18:07
【问题描述】:

我们正在使用 boost 线程特定指针来仅为该特定线程存储一些全局数据。下面是当有人调用 GetInstance() 时我们返回的单例。

我的问题是,与普通指针访问相比,获取线程特定指针 (m_tspConnectionManager.get();) 大约需要多长时间?

我使用了下面的代码(我调用了 .get() 方法两次),完成整个函数大约需要 3 秒。

  typedef boost::thread_specific_ptr<ConnectionManager> ConnMgrPtr;
    static ConnMgrPtr m_tspConnectionManager;
    static ConnectionManager* GetInstance()
            {
                if(!m_tspConnectionManager.get())
                {
                    //first time called by this thread
                    //ConnectionManager* to be used in all subsequent calls from this thread
                    m_tspConnectionManager.reset(new ConnectionManager());
                }
                return m_tspConnectionManager.get();
            }

现在,我将上面的代码更改为只调用一次 .get() 方法,大约需要 1.9 秒。

    static ConnectionManager* GetInstance()
            {
                ConnectionManager* pConnMgr = m_tspConnectionManager.get();
                if(pConnMgr == NULL)
                {
                    //first time called by this thread
                    //ConnectionManager* to be used in all subsequent calls from this thread
                    m_tspConnectionManager.reset(new ConnectionManager());
                }
                return pConnMgr != NULL ? pConnMgr : m_tspConnectionManager.get();
            }

所以,只要不调用 .get() 方法,我就可以看到 1.1 秒的性能提升。我一直在试图了解我们如何获得收益? 注意:这个收益可能是多次调用 GetInstance() 函数的集体收益。只是想了解这里的单个呼叫增益。

【问题讨论】:

  • thread_specific_ptr::get() 绝对不可能花费 1.1 秒来执行。即使在调试模式下。你是如何安排这些事情的?
  • 对不起,我没有正确澄清,但 1.1 秒是集体收益,即多次调用函数。我只是想了解大概的单次通话增益。

标签: c++ windows multithreading performance thread-local-storage


【解决方案1】:

get() 不太可能花费很多时间(当然,它比不调用get() 慢。)使用 TLS 的“正常”实现,您的对象最多是三个指针间接距离。 (线程块寄存器-> TLS 块-> 你的指针。)但是如果你调用GetInstance() 足够多,那么任何减速都可能变成一个很大的减速。

我会看看GetInstance() 被调用的频率。尝试通过缓存返回的指针来减少该数字。当然,第二种实现比第一种更可取。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    相关资源
    最近更新 更多