timeit

安装

1.下载最新版本
http://www.swig.org/download.html
2.安装pcre

yum install pcre-devel

3.安装swig

tar -zxvf swig-3.0.12.tar.gz
cd swig-3.0.6
./configure
make
sudo make install

编译模块

1.编写c

/* File : example.c */

#include <time.h>
double My_variable = 3.0;

int fact(int n) {
 if (n <= 1) return 1;
 else return n*fact(n-1);
}

int my_mod(int x, int y) {
 return (x%y);
}

char *get_time()
{
 time_t ltime;
 time(&ltime);
 return ctime(&ltime);
}

2.编写swig接口

/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
%}

extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();

3.编译

swig -python example.i # 根据接口生成wrap文件
gcc -c -fPIC example.c example_wrap.c -I/home/test/program/anaconda3/include/python3.6m # 编译c源文件和swig生成的wrap文件(这里一定要添加-fPIC参数,否则下一步会出错)
ld -shared example.o example_wrap.o -o _example.so //链接编译后的文件,并生成shared object文件,就是python的库

生成的example.py_example.so就是所需要的模块

测试性能

1.c接口测试

>>> import timeit
>>> timeit.timeit("example.fact(5)",setup='import example')
0.20446171000003233

2.python脚本测试
2.1.用python实现fact方法

def fact(n):
    if n <= 1:
        return 1
    else:
        return n*fact(n-1)

2.2.测试性能

>>> import timeit
>>> timeit.timeit("fact(5)",setup="from py import fact")
0.5462862730000779

参考文献:
http://www.swig.org/translations/chinese/tutorial.html
http://makaidong.com/wuxianfeng1987/1/191_9507614.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值