您的位置 首页 golang

Golang构建Python高性能模块

package main

import "C"

//指定那些函数能被外部调用

//export test

func test()  int{

    //计算 0-1000000000 的和

    var s int

    for a := 0; a <= 10000000000; a++ {

        s += a

     }

     return s

}

​//pxport addstr

func addstr(a,b * C.char) *C.char{

        merge := C.GoString(a) + C.GoString(b)

        return C.CString(merge)

}

func main(){

}

编译生成动态链接库,生成的.so文件可以被python加载并调用

但是有一个需要注意的地方:

Python是利用ctypes来跟so模块进行交互,其中存在着一个代码的翻译过程,包括数据类型的翻译,如果需要传参获取接收返回值,需要在golang中将参数按照下表对应,定义成C语言的数据类型。

python,ctypes , c 对应类型参考 python 官方文档:https://docs.python.org/3.5/library/ctypes.html

这里列举几个常用的数据类型

go文件编译成动态链接库

go build -buildmode=c-shared -o learn.so learn.go

from ctypes import CDLL

add = CDLL('./test.so').addstr #调用go模块

# 显式声明参数和返回的期望类型

add.argtypes = [ctypes.c_char_p, ctypes.c_char_p]

add.restype = ctypes.c_char_p

print(add('test','test'))

# 无参数,则可直接调用

t = CDLL('./test.so').test     #调用go模块

print(t())

python 中调用go模块,并统计两个模块循环10亿次累加的时间,查看go跟python执行效率

# coding=utf-8

import time

from ctypes import CDLL

import ctypes

def xu():

    # python 计算累加

    sum = 0

    for i in range(0,1000000000+1):

        sum += i

    return sum

if __name__ =="__main__":

    add = CDLL('./test.so').addstr #调用go模块addstr方法

    # 显式声明参数和返回的期望类型

    add.argtypes = [ctypes.c_char_p, ctypes.c_char_p]

    add.restype = ctypes.c_char_p

    print(add('haha','hehe'))

    # go 10亿次累加

    start = time.time()

    t = CDLL('./test.so').test #调用go模块test方法

    t.restype = ctypes.c_int64 # 返回int64类型

    print("go执行结果:%s"%t())

    end = time.time()

    print("go :1000000000 累加耗时 %.2f" %(end-start))

    # python累加10亿次

    start = time.time()

    print("python执行结果:%s"%xu())

    end = time.time()

    print("python :1000000000 累加耗时 %.2f" %(end-start))

运行结果: 运行速度差近200倍!


文章来源:智云一二三科技

文章标题:Golang构建Python高性能模块

文章地址:https://www.zhihuclub.com/415.shtml

关于作者: 智云科技

热门文章

网站地图