在本次项目中有比较多的直接调命令的地方,所以就在想用system函数还是popen函数,哪个效率更高呢。在网上找了找,看见说什么的都有,而且感觉他们的测试方法也有点不太赞同,所以就自己写了个测试代码,看看到底哪个效率更高点。关于system函数和popen函数的基本知识在这就不再提了,只发表一下自己的测试方法和测试结果:
平台:Ubuntu release 7.04
Linux 内核:2.6.20
CPU:双核 i3
GCC:4.1.2
代码:
int main(int argc, char *argv[])
{
FILE *fp=NULL;
int i = 0;
clock_t start = 0, end = 0;
double t = 0.00;
start = clock();
for(i=0; i<10000; i++)
{
system("ls -l > /dev/null");
//fp=popen("ls -l > /dev/null","r");
//pclose(fp);
}
end = clock();
t = (double)(end - start) / CLOCKS_PER_SEC;
printf("%f seconds is used\n", t);
return 0;
}
测试结果:
循环1000次:
system:
0.040000 seconds is used
popen:
0.040000 seconds is used
循环10000次:
system:
0.340000 seconds is used
popen:
0.460000 seconds is used
结论:system的效率更高
注:可能测试方法不太正确,请指出;有不同意见者请提出。欢迎讨论!