我有一个任务,我必须在Linux上用C编写程序(我使用CentOS),它使用线程/进程来确定CPU的内核数量。 首先,我尝试以毫秒/微秒的方式打印当前时间,因为我知道可以运行1线程/内核(或2与HT)。但是,以毫秒为单位,超过10个线程印刷的时间相同,而在几微秒内则没有一个是相同的。 其次,我试着用时钟测量线程的执行时间,由于我有4个内核,所以同时执行4个线程的执行时间应该和执行1的时间差不多。但是我的程序中没有一个可以让我更接近CPU的数量。 你能帮我一些建议吗?发现使用线程的CPU核心数量
程序打印当前时间:
pthread_t th[N];
void* afis()
{
//time_t now;
//time(&now);
//printf("%s", ctime(&now));
struct timeval start, end;
long mtime, seconds, useconds;
gettimeofday(&start, NULL);
// usleep(2000);
gettimeofday(&end, NULL);
seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;
mtime = seconds + useconds;
printf("Thread with TID:%d Elapsed time: %ld microsecons\n",(unsigned int)pthread_self(), mtime);
}
int main()
{
int i;
for (i=0;i<N;i++)
{
pthread_create(&th[i],NULL,afis,NULL);
}
for(i=0;i<N;i++)
{
pthread_join(th[i],NULL);
}
return 0;
}
计划测量处理时间:
pthread_t th[N];
void* func(void* arg)
{
int x;
int k;
int n=(int)arg;
for(k=0;k<10000000;k+=n)
{
x=0;
}
}
int main()
{
int i,j;
for (i=0;i<N;i++)
{
clock_t start, end, total;
start=clock();
for(j=0;j<i;j++)
{
printf("execution nr: %d\n",i);
pthread_create(&th[j],NULL,func,(int*)i);
}
for(j=0;j<i;j++)
{
pthread_join(th[j],NULL);
}
end=clock();
printf("start = %ld, end = %ld\n", start, end);
total=((double)(end-start))/ CLOCKS_PER_SEC;
printf("total=%ld\n",total);
}
return 0;
}
我在答案中添加了一个想法。 – Theolodis 2014-10-08 15:19:34