出于性能方面的考虑,我曾考虑将go应用于我未来的项目,但有一个很大的惊喜:go的运行时间是13.974427秒,而pythons的运行时间只有6.593028783798218秒 不到一半!你知道吗
XML文件大小超过300MB。 这是Python的密码:
from lxml import objectify
import time
most = time.time()
root = objectify.parse(open(r"c:\temp\myfile.xml", 'rb')).getroot()
if hasattr(root, 'BaseData'):
if hasattr(root.BaseData, 'SzTTs'):
total_records = 0
for sztt in root.BaseData.SzTTs.sztt:
total_records += 1
print("total_records", total_records)
print("Time elapsed: ", time.time()-most)
下面是简化的go代码:
package main
// An example streaming XML parser.
import (
"encoding/xml"
"fmt"
"io"
"os"
"time"
)
var inputFile = "c:\\temp\\myfile.xml"
type SzTTs struct {
Sztt []sztt
}
type sztt struct {
}
func main() {
xmlFile, err := os.Open(inputFile)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer xmlFile.Close()
d := xml.NewDecoder(xmlFile)
total1 := 0
total2 := 0
start := time.Now()
for {
// Read tokens from the XML document in a stream.
t, err := d.Token()
// If we are at the end of the file, we are done
if t == nil || err == io.EOF {
fmt.Println("The end")
break
} else if err != nil {
log.Fatalf("Error decoding token: %s", err)
}
// Inspect the type of the token just read.
switch se := t.(type) {
case xml.StartElement:
if se.Name.Local == "SzTTs" {
var p SzTTs
// decode a whole chunk of following XML into the
// variable p which is a Page (se above)
if err = d.DecodeElement(&p, &se); err != nil {
log.Fatalf("Error decoding item: %s", err)
}
for i := range p.Sztt {
total1 = i
}
}
default:
}
}
fmt.Printf("Total sztt: %d \n", total1)
fmt.Printf("Elapsed time %s", time.Since(start))
}
为什么会有这么大的差别?你知道吗
扩展我的评论-这是预期的。你知道吗
Go的
encoding/xml
是用纯Go编写的,而lxml
基本上是用C编写的。它使用Cython,Cython从类似Python的DSL生成C代码。你知道吗2x并不是一个巨大的性能差异,但是如果最后一点性能对你来说都很重要,那么考虑使用另一个Go包——一个包装了优化的C实现的包。你知道吗
例如,libxml(最流行的C实现之一)有几个包装器:
我预计这将比
encoding/xml
快得多。你知道吗Edid(2019-07-22):这个问题激发了我对write more about streaming XML performance in Go和a new wrapper for the libxml SAX interface的兴趣。你知道吗
相关问题 更多 >
编程相关推荐