11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python with Go

Posted at

何番煎じかわからないが、Golangで書いたパッケージをPython(多言語)から利用

##1.構成

Python : 2.7
Golang : 1.7
OS : CentOS release 6.8
Memory : 2048MB
CPU : 3core

PythonLibrary
ctypes

##2. 準備

fib.go
package main

import "C"

//export fib
func fib(n uint) uint {
    if n <= 1 {
        return n
    }
    return fib(n-1) + fib(n-2)
}

func main() {}

build

go build -o fib.so  -buildmode=c-shared fib.go
fib_go.py
from ctypes import *

lib = cdll.LoadLibrary("./fib.so")

## arg
lib.fib.argtypes = [c_longlong]
## return
lib.fib.restype = c_longlong
print "fib  %d" % lib.fib(40)

fib.py
#!/usr/bin/env python

def fib(n):
    if n <= 1:
        return n
    else:
        return fib(n-1) + fib(n-2)

print(fib(40))

##3.計測

fib_go.py

#time python fib_go.py
fib  102334155

real	0m1.171s
user	0m1.105s
sys	0m0.071s

fib.py

#time python fib_go.py
102334155

real	0m46.598s
user	0m46.449s
sys	0m0.030s
11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?