我一直在处理一些需要转换成UTF-8的大文件,因为像iconv这样的传统工具无法使用这些文件。所以我决定在Go中编写自己的工具,但是我注意到这种编码转换在Go中相当慢。这是我的密码:
package main
import (
"fmt"
"io"
"log"
"os"
"golang.org/x/text/encoding/charmap"
)
func main() {
if len(os.Args) != 3 {
fmt.Fprintf(os.Stderr, "usage:\n\t%s [input] [output]\n", os.Args[0])
os.Exit(1)
}
f, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
out, err := os.Create(os.Args[2])
if err != nil {
log.Fatal(err)
}
r := charmap.ISO8859_1.NewDecoder().Reader(f)
buf := make([]byte, 1048576)
io.CopyBuffer(out, r, buf)
out.Close()
f.Close()
}
Python中的类似代码的性能要高得多:
import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open("FRWAC-01.xml", "r", "latin_1") as sourceFile:
with codecs.open("FRWAC-01-utf8.xml", "w", "utf-8") as targetFile:
while True:
contents = sourceFile.read(BLOCKSIZE)
if not contents:
break
targetFile.write(contents)
我确信我的Go代码会快得多,因为一般来说,Go中的I/O速度很快,但事实证明它比Python代码慢得多。有没有办法改进围棋项目?你知道吗
这里的问题是,在这两种情况下,您没有比较相同的代码。此外,Go中的IO速度与python没有太大区别,因为它们进行相同的系统调用。你知道吗
在python版本中,默认情况下会缓冲文件。在Go版本中,当您将
io.CopyBuffer
与1048576
字节缓冲区一起使用时,解码器将直接对无缓冲区文件进行所需大小的Read
调用。你知道吗用
bufio
包装文件IO将产生类似的结果。你知道吗相关问题 更多 >
编程相关推荐