Wednesday 26 November 2008

efficiency of python calling c exetuable

python 可以用popen调用一个c语言的可执行程序。但是效率如何呢?

1)一个c程序: 调用一个循环求和从1到1000的function 10000次。
之所以要调用循环求和从1到1000,是因为这个function要声称另外的一个可执行文件供python调用,所以外部框架c和python都差不多,就是要往复调用这个function,以得出python与c的沟通效率。
#######################
/*
* File: newmain.c
* Author: cross
*
* Created on 26 November 2008, 16:08
*/

#include <stdio.h>
#include <stdlib.h>

struct timeb {
time_t time;
unsigned short millitm;
short timezone;
short dstflag;
};
//ftime returns a struct with above structure.

int internal_loop(){
int ii=0,ss=0;
while (ii<1000)
{
ss+=ii;
ii++;
}
printf("%i\n",ss);
return ss;
}

int main(int argc, char** argv) {

struct timeb t1,t2;
double i=0,s=0;

ftime(&t1);

int repeat = 10000;
while(i<repeat){
s+=internal_loop();
i++;
}

ftime(&t2);
printf("%.1f\n",s);

printf("time = %ld.%d\n",t1.time,t1.millitm);
printf("time = %ld.%d\n",t2.time,t2.millitm);


return (EXIT_SUCCESS);
}


##################

2)以上的internal_loop function被单独生成一个c的可执行文件b.o,供python调用。以下是python代码。
##################

import datetime
import os

t1= datetime.datetime.now()

j=0
k=1000
for i in range(1,k):
printed=os.popen('/home/cross/NetBeansProjects/Application_2/b.o')
printed.readlines()
printed.close()

print # to print a new line

t2= datetime.datetime.now()

tstr=[(t2-t1).seconds,(t2-t1).microseconds] # the attributes of timedelta class: senconds and microseconds, from http://docs.python.org/lib/datetime-timedelta.html#l2h-602
print 'Repeated sum of 1-1000 ',k,' times : '
print tstr

###############

3) 只用python单独完成和1)一样的过程,python代码如下:
########################
import datetime

t1= datetime.datetime.now()

k=10000
for i in range(1,k):
    j=0
    for ii in range(1,1000):
        j=j+ii
    print j

print # to print a new line

t2= datetime.datetime.now()

tstr=[(t2-t1).seconds,(t2-t1).microseconds] # the attributes of timedelta class: senconds and microseconds, from http://docs.python.org/lib/datetime-timedelta.html#l2h-602
print 'Repeated sum of 1-1000 ',k,' times : '
print tstr

#####################


总结
如果成功运行以上两个程序,同样是运行10000次,1)耗时274毫秒;2)20秒。
可见python与其他程序通过popen这种字符沟通的效率是比较低的。以上,1)是同一个程序调用一个子函数,速度当然是最理想的。而2)是通过console的字符交换得以沟通,这种效率当然低,甚至这还远不如主程序和子程序的沟通效率。

通过1)和3)的比较,可以很容易看出来python的语法简单,但是python比c慢也是事实,3)用时3.8秒。

No comments:

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter