Cython_Ubuntu_(get_angle)

Python有一个标准库disutils,可以用来构建、打包、分发Python工程。

1. 编写Cython程序
# get_angle_cython.pyx
cimport cython
import math

@cython.boundscheck(False)
@cython.wraparound(False)
cdef float _get_angle(float x, float y):
    cdef float angle
    cdef float tan_yx

    angle = 123
    if y == 0 :
        if x < 0:
            angle = 180
        else:
            angle =  0
    if x == 0 :
        if y > 0:
            angle = 90
        else:
            angle =  270   
    else: 
        tan_yx = abs(y)/abs(x)
        if y > 0 and x < 0:
            angle = 180 - math.atan(tan_yx)*180/math.pi #90-180
        elif y > 0 and x > 0:
            angle =  math.atan(tan_yx)*180/math.pi #0-90
        elif y < 0 and x < 0:
            angle = 180 + math.atan(tan_yx)*180/math.pi #180-270
        elif y < 0 and x > 0:
            angle = 360- math.atan(tan_yx)*180/math.pi #270-360
    return angle

def get_angle(x, y):
    return _get_angle(x, y)




2. 编写编译配置文件
from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules=cythonize("get_angle_cython.pyx"))

3. 编译命令

项目所在目录下,命令行输入:

python setup.py build_ext --inplace

–inplace 表示在在当前目录下生成.so文件。

编译之后目录中增加文件:
在这里插入图片描述

4. 命令行调用
import get_angle_cython
# 我们看到该so文件直接就被导入了,至于中间的是对应的解释器版本、操作系统等信息
# 可以不用管,甚至你删掉只保留get_angle_cython.so也是可以的。
print(get_angle_cython) # 打印文件路径
print(get_angle_cython.get_angle(100, 200))

在这里插入图片描述

5. 对比运行时间

对比Python代码和Cython代码运行时间。

import get_angle
import get_angle_cython
%timeit -n 100 -r 3 get_angle.get_angle(100, 200)
%timeit -n 100 -r 3 get_angle_cython.get_angle(100, 200)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值