首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >提升线程开销

提升线程开销
EN

Stack Overflow用户
提问于 2012-08-20 12:57:45
回答 1查看 2.7K关注 0票数 3

我发现在下面这个简单的程序中,boost线程开销有三个数量级的计时开销。有没有什么方法可以减少这种开销并加速fooThread()调用?

代码语言:javascript
复制
#include <iostream>
#include <time.h>
#include <boost/thread.hpp>
#include <boost/date_time.hpp>
typedef uint64_t tick_t;
#define rdtscll(val) do { \
    unsigned int __a,__d; \
    __asm__ __volatile__("rdtsc" : "=a" (__a), "=d" (__d)); \
        (val) = ((unsigned long long)__a) | (((unsigned long long)__d)<<32); \
    } while(0)


class baseClass {
 public:
   void foo(){
             //Do nothing 
        }
       void threadFoo(){
          threadObjOne = boost::thread(&baseClass::foo, this);
              threadObjOne.join();
   }

 private:
   boost::thread threadObjOne;
 };

int main(){
   std::cout<< "main startup"<<std::endl; 
   baseClass baseObj; 
   tick_t startTime,endTime;
       rdtscll(startTime);
   baseObj.foo();
   rdtscll(endTime);
   std::cout<<"native foo() call takes "<< endTime-startTime <<" clock cycles"<<std::endl;
   rdtscll(startTime);
   baseObj.threadFoo();
       rdtscll(endTime);
       std::cout<<"Thread foo() call takes "<< endTime-startTime <<" clock cycles"<<std::endl;  
  }

您可以使用g++ -lboost_thread-mt main.cpp对其进行编译,下面是我机器上的示例输出:

代码语言:javascript
复制
main startup
native foo() call takes 2187 clock cycles
Thread foo() call takes 29630434 clock cycles
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-20 14:26:02

你真正想要的是一个线程池:

代码语言:javascript
复制
#include "threadpool.hpp"

int main()
{
    boost::threadpool::pool threadpool(8);  // I have 4 cpu's
                                            // Might be overkill need to time
                                            // to get exact numbers but depends on
                                            // blocking and other factors.

    for(int loop = 0;loop < 100000; ++loop)
    {
        // schedule 100,000 small tasks to be run in the 8 threads in the pool
        threadpool.schedule(task(loop));
    }

    // Destructor of threadpool
    // will force the main thread to wait
    // for all tasks to complete before exiting
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12032457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档