为什么一个子线程的执行时间多于整个应用程序的执行时间

时间:2013-06-25 00:14:13

标签: c++ linux multithreading performance

这是一个多线程应用程序,我在下面编写的一个子线程中编写了用于计算线程运行函数执行时间的代码:

       class CThreadObject{
           public:
                ...
                unsigned long GetTime(){
                   struct timeval val;
                   gettimeofday(&val, NULL);
                   return (val.tv_sec * 1000000 + val.tv_usec);
                }

                static void* Run(void *param){ // thread function
                    while (1){
                          static unsigned long ExecTime = GetTime();
                          unsigned long LastExecTime = 0;

                          if (TurnOnTest()){
                              LastExecTime = ExecTime;
                              ExecTime = GetTime();
                             mQueue.push_back(ExecTime - LastExecTime);                     
                              //std::deque<unsigned long> mQueue
                          }

                          //some other jobs such as 
                          //I/O demultiplex and events dispatching
                          .......
                    };

                    return NULL;
                }  

                void PrintStatistics(){
                    unsigned long tmp = 0;
                    while(mQueue.size()){
                          tmp += *mQueue.begin();
                          mQueue.pop_front();
                    }

                    printf("the total time is %lu\n", tmp);
                }

           private:
                ...
                std::deque<unsigned long> mQueue;
                pthread_t  mThread;
       };

应用程序只执行1分钟,但我发现时间累计了 gQueue的所有元素都是175秒,大于整个应用程序的时间。 为什么会这样?

[UPDATE]
增加了一个功能--PrintStatistics()

1 个答案:

答案 0 :(得分:2)

你的线程没有测量它们的运行时间;他们正在测量他们的开始时间和结束时间之间的差异(大致)。在那段时间里,他们不是经常跑;由于有多个线程(以及您机器上的多个进程),它们共享处理器时间,因此在开始和结束之间的某个时间段处于空闲状态。

想象一下:上午9点有两个人上班。他们轮流执行某项任务 - 例如驾驶叉车 - 并继续关闭,在执行任务和休息之间交替,直到下午5点,此时他们退出。他们一起工作了16个小时,但叉车只运行了8个工作日(这里,你的程序的运行时间)只有8个小时。您的程序正在测量时间差异。