程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Briefly talk about the difference between Python and go

編輯:Python

background

The main language in work is Python, Tools for performance testing this year , because GIL lock Why ,Python The performance of is really poor , You need to learn a high-performance language to generate the pressure side of performance testing . So I set my eyes on the current rookies Go. After a period of study , Also wrote a gadget , Remember the difference between the two languages .

demand

The tool is a little reptile , Iteration records of a product used to climb a website , The implementation logic is after running the script , The user enters certain elements from the command line ( product ID etc. ) after , Script export a Excel File out .

The original version used Python Written ,30 It's done in less than lines of code . This time Go rewrite , The amount of code is 110 Row or so .

Accept input

The first step is to accept the input from the command line , Tools should be used by non-technical personnel , Make one CLI It's not reasonable to , The effect is to input the content line by line , use Python It's very easy to implement , like this :

app_id = raw_input(' Please enter app_id: ')
app_analysis = raw_input(' Please enter analysis: ')

After the implementation, it goes down line by line , But with Go It hurts a little , The complete code is as follows :

func getPara() (string, string) {
var i = 0
var appId, analysis string
fmt.Print(" Please enter appId:")
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
text := scanner.Text()
if i == 0 {
appId = text
fmt.Print(" Please enter analysis:")
} else if i == 1 {
analysis = text
fmt.Print(" Program initialization data completed .... Please press any key to continue ")
} else {
break
}
i++
}
return appId, analysis
}

Go To achieve CLI Very convenient , But when it comes to this line by line input , Keep listening Scan(), So there is the circulation of egg pain , And the information must be printed first , Then listen to the content , The overall writing process is disgusting , Maybe there is no better way , It's really against the sky .

Send a request

It is convenient to send a request , There is not much difference between the two languages , At least I wrote Get This is the request .

Python
params = {
"analysis": app_analysis,
"appid": app_id,
"country": 'cn'
}
r = requests.get(url, params)
Go
q := req.URL.Query()
q.Add("appid", appId)
q.Add("analysis", analysis)
q.Add("country", "cn")
req.URL.RawQuery = q.Encode()
var resp *http.Response
resp, _ = http.DefaultClient.Do(req)

Return result processing

In the processing of returned results ,Python The way you handle it is simply too friendly , Call directly json Just deal with it .

result = r.json()

however Go It hurts a little , Because it is a static language , So you need to define the data format before unpacking data , For example, the following structure definitions must be made for the returned content :

type ResultInfo struct {
Code int
Msg string
Version []VersionInfo
}
type VersionInfo struct {
Version string `json:"version"`
ReleaseTime string `json:"release_time"`
ReleaseNote string `json:"release_note"`
AppName string `json:"app_name"`
SubTitle string `json:"subtitle"`
}

first ResultInfo Is the returned data , Among them Version Is also an array object , So we need to define an array object , In this way, the method can be called to unpack .

body, _ := ioutil.ReadAll(resp.Body)
var rst = ResultInfo{}
if err := json.Unmarshal(body, &rst); err != nil {
fmt.Println(err)
}

Write data to the Excel

This part calls the third-party libraries , So there is no comparability , The implementation of the code depends entirely on third-party packages .

Omnipresent err != nil

Go The exception capture mechanism of is similar to Python perhaps Java Is not the same ,Python The exception capture of uses try,except To wrap the code block , and Go I'm using one error object , So all of them Go The code will be full of

if err != nil {
return nil, err
}

This kind of shit , This exception mechanism is used when reading code , It's disgusting , It has greatly affected the reading experience .

After roast

Basically, from the process of writing code ,Python The coding efficiency of Go A lot higher ,Go It is claimed that grammar is flexible , It can greatly improve the coding efficiency , There is no such thing as , Limited to static languages , Compared with Python In this dynamic language , The gap in coding efficiency is still very large . It can only be said that it is more efficient than other static languages .

however !!!

Go Is more efficient than Python Too high . for instance , There is an algorithm for calculating Fibonacci numbers ,Go The implementation is as follows :

func main() {
const n = 40
starttime := time.Now()
fibN := fib(n)
endtime := time.Now()
cost_time := endtime.Sub(starttime)
fmt.Println(cost_time)
fmt.Printf("\rFibonacci(%d) = %d\n", n, fibN)
}
func fib(x int) int {
if x < 2 {
return x
}
return fib(x-1) + fib(x-2)
}

A very simple recursion , When N by 40 When ,Go Spent about 1 Seconds or so , The results are as follows :

876.838ms( Elapsed time ) Fibonacci(40) = 102334155

Let's change to Python

def fib(x):
if x<2:
return x
return fib(x-1)+fib(x-2)
if __name__ == '__main__':
import time
begin = time.time()
print fib(40)
end = time.time()
print end-begin

Same execution logic , The result of execution is :

102334155
52.8657081127( Elapsed time )

WTF!!! use Go To deal with efficiency is Python Of 50 More than times .

It's not over yet. , When the tools are finished, they should always be used by others ,Python After you've written , If used by a non-technical person , that ...

 Users : How to use it ?
I : You pretend Python, Then configure the environment variables , By the way, the requests Kuhe xlwt Also install the library .
I : To install these two libraries, you need to install them first pip.
Users : Black question mark face !!!!!

If you use Go To write , Just send it after packing

 Users : How to use it ?
I : You double click , You can enter whatever you want 

If the user is using Windows System , That's no problem ,

CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build xxx.go

Pack it directly into exe file .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved