これは、スレッド実行関数の実行時間を計算するコードの下に記述したサブスレッドの 1 つで、マルチスレッド アプリケーションです。
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]
もう 1 つの関数を追加 -- PrintStatistics()