【发布时间】:2014-10-08 13:26:38
【问题描述】:
我有一个任务,我必须在 Linux 上用 C 语言编写一个程序(我使用 CentOS),它使用线程/进程来确定 CPU 的内核数量。 首先,我尝试以毫秒/微秒为单位打印当前时间,因为我知道可以运行 1 个线程/核心(或 2 个使用 HT)。但是以毫秒为单位,超过 10 个线程打印了相同的时间,以微秒为单位,没有一个线程是相同的。 其次,我尝试用时钟测量线程的执行时间,鉴于我有 4 个内核,4 个线程同时执行的时间应该几乎与执行 1 一样长。但是我的程序都不能让我更接近这个数字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;
}
【问题讨论】:
-
我在答案中添加了一个想法。
标签: c multithreading cpu