golang python性能_Golang构建Python高性能模块
package?main
import?"C"
?
//指定那些函數(shù)能被外部調(diào)用
//export test
func?test()? int{
//計(jì)算 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(){
}
編譯生成動(dòng)態(tài)鏈接庫,生成的.so文件可以被python加載并調(diào)用
但是有一個(gè)需要注意的地方:
Python是利用ctypes來跟so模塊進(jìn)行交互,其中存在著一個(gè)代碼的翻譯過程,包括數(shù)據(jù)類型的翻譯,如果需要傳參獲取接收返回值,需要在golang中將參數(shù)按照下表對應(yīng),定義成C語言的數(shù)據(jù)類型。
這里列舉幾個(gè)常用的數(shù)據(jù)類型
go文件編譯成動(dòng)態(tài)鏈接庫
go build -buildmode=c-shared -o learn.so learn.go
from?ctypes?import?CDLL
add?=?CDLL('./test.so').addstr?#調(diào)用go模塊
# 顯式聲明參數(shù)和返回的期望類型
add.argtypes?=?[ctypes.c_char_p, ctypes.c_char_p]
add.restype?=?ctypes.c_char_p
print(add('test','test'))
?
# 無參數(shù),則可直接調(diào)用
t?=?CDLL('./test.so').test ? ? #調(diào)用go模塊
print(t())
python 中調(diào)用go模塊,并統(tǒng)計(jì)兩個(gè)模塊循環(huán)10億次累加的時(shí)間,查看go跟python執(zhí)行效率
# coding=utf-8
import?time
from?ctypes?import?CDLL
import?ctypes
?
def?xu():
# python 計(jì)算累加
sum?=?0
for?i?in?range(0,1000000000+1):
sum?+=?i
return?sum
?
if?__name__?=="__main__":
add?=?CDLL('./test.so').addstr?#調(diào)用go模塊addstr方法
# 顯式聲明參數(shù)和返回的期望類型
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?#調(diào)用go模塊test方法
t.restype?=?ctypes.c_int64?# 返回int64類型
print("go執(zhí)行結(jié)果:%s"%t())
end?=?time.time()
print("go :1000000000 累加耗時(shí) %.2f"?%(end-start))
?
# python累加10億次
start?=?time.time()
print("python執(zhí)行結(jié)果:%s"%xu())
end?=?time.time()
print("python :1000000000 累加耗時(shí) %.2f"?%(end-start))
運(yùn)行結(jié)果: 運(yùn)行速度差近200倍!
總結(jié)
以上是生活随笔為你收集整理的golang python性能_Golang构建Python高性能模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新手摆地摊卖什么好 这几种投资都比较少
- 下一篇: quartz持久化是指_面试必问:Red