这是一个多线程的应用程序中,我写了下面的代码来计算线程运行函数的执行时间的子线程的一个多:为什么一个子线程的执行时间比整个应用
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()
不是答案,但我建议您在进行这些类型的时间测量时使用'clock_gettime(CLOCK_MONOTONIC)'。 'gettimeofday()'受系统时间影响,系统时间可能会改变(DST,NTP等) –
当你说“我发现qQueue的所有元素累积的时间为175秒”时,你会怎样这是什么意思?你是否将gQueue的所有成员加在一起?如果是这样,那将是错误的,因为线程同时运行,并且每个单独的线程可以运行程序的长度。请在应用程序运行结束后发布gQueue的内容,以帮助我们理解您的问题。 – Nathanael
你似乎在每次循环迭代中将'LastTime'初始化为0 ... –