vi test_printf.c
#include<stdio.h>
#include<pthread.h>
#include<math.h>
#include<unistd.h>
#define NBR_THRS 8
void* busywork(void* arg) {
long t = (long) arg;
double res = 0;
for(long i =0; i< t; i++)
res += sin(i) * cos(i);
//printf("res=%f\n", res);
return NULL;
}
int main() {
pthread_t ID[NBR_THRS];
long i;
for(i=0; i<NBR_THRS; i++)
pthread_create(&ID[i], NULL, busywork, (void*) 100000000);
for(i=0; i<NBR_THRS; i++)
pthread_join(ID[i], NULL);
}
本程序若去除子程序中的打印语句,在我的电脑上运行仅花0.002秒;若加上子程序中的打印语句,则花20.635秒之多!请大侠们解释下为啥差别那么大?编译都用 gcc -Wall -O3 demo.c -lpthread -lm
本文探讨了一个C语言多线程程序中,子线程进行大量计算时,加入打印语句前后性能的巨大差异。通过对比两种情况下的运行时间,解释了为何简单的打印操作会导致程序运行时间显著增加。
4348

被折叠的 条评论
为什么被折叠?



