繁体   English   中英

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

[英]Why execution time of one sub-thread is more than that of the whole application

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

       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()

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

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

暂无
暂无

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

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