Calling go in a python program

Although python has many advantages, it has a fatal disadvantage that the running speed is too slow. When a python program needs some modules with a large amount of calculation, it usually calls the code of c or c++ to rewrite it, but the cost of writing code in c/c++ is too high , consumes too much manpower. Then think of a compromise method is to use the golang language.

Although golang's performance is not as good as c, golang's inherent high concurrency, super fast compilation speed, and its own garbage collection mechanism, do not require developers to manage memory by themselves, and have high development efficiency. So when the python program encounters a large amount of calculation, you can consider calling the go module.

 

Let's see how to build a go python module:

package main

import "fmt"
import "C"


// export test          
  // Specify which functions can be called externally

func test(){
// test function loops 1000000 times 
    for a := 0 ; a < 1000000 ; a++ {
        fmt.Printf( " The value of a is: %d\n " , a)
     }

}


func main(){
    fmt.Println("hello world")
    test()
}

 

Compile and generate a dynamic link library, and the generated .so file can be loaded and called by python

go build -buildmode=c-shared -o hello.so src/hello.go

  

Call the go module in python, and count the time that the two modules loop one million times, check the execution efficiency of go and python

# coding=utf-8
import time
from ctypes import CDLL

def xu():
    for i in range(0,1000000):
        print(u"a 的值为: %d\n"%i)

if __name__ =="__main__":
    py_start = time.time()
    coins()
    py_end = time.time()

    lib = CDLL( ' ./hello.so ' ) # call the go module

    start = time.time()
    lib.test()
    go = time.time()-py_end
    
    print("go",go)
    py = py_end-py_start
    print("python",py)

    print ( ' Speed ​​comparison: %f ' %(py/go))

 From the point of view of looping one million times alone, go is more than 2 times more efficient.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324783660&siteId=291194637