读书人

关于运用clock()来测量任务的执行时

发布时间: 2013-01-05 15:20:40 作者: rapoo

关于使用clock()来测量任务的执行时间差的疑问

#include <stdio.h>
#include <stdlib.h>
#include<time.h>
#include<pthread.h>
#include<unistd.h>
#include<errno.h>
#define TIMEGAP 1
void *fun_1()
{
printf("tid = %d\n",pthread_self());
clock_t start,end2;
start=clock(); //线程开始
double duration ;
while(1)
{
duration=(double)(end2-start)/CLOCKS_PER_SEC;
if(duration>1)
{
printf("time arrived!\n");
break;
}
end2=clock(); //结束时间
printf("end2=%d \n",end2);
usleep(1000);
}


}

int main()
{
clock_t start,end1;
double duration;
long i = 10000000L;
pthread_t tid;
int ret=pthread_create(&tid,NULL,fun_1,NULL);
if(!ret)
perror("pthread_create");

start=clock(); //主线程中测量执行时间,
while(i--);
end1=clock();
printf("end1=%d \n",end1);
duration=(double)(end1-start)/CLOCKS_PER_SEC;
printf("%f ",duration);
return 0;
}


这里有个疑问问什么线程的ID是负数,
还有为什么我的线程里的while语句执行的不是自己想要的??
貌似没执行打印语句啊


-----------------------------各位能给我看一下吗。
http://bbs.chinaunix.net/thread-4057635-1-2.html这是我在另外看到的一边帖子
[解决办法]
因为线程ID就是一个无符号长整型,并且值很大,你用%d自然打出来负数,
你要什么打印结果,把实际的结果贴出来
[解决办法]
clock是进程的大概执行时间,用clock无法测量一个线程的执行时间,记住线程是共用进程的内存空间和资源,这个资源就包括clock获取的进程执行时间。

读书人网 >UNIXLINUX

热点推荐