从数字数组中加/减值的最快方法是什么?

我有下面的代码,想从每个元素中添加/减去值“1”。最快的方法是什么?询问是因为我在 myByte 数组中有 100 万个元素。下面的代码只显示了 3,但如果有一百万,它会花费很长时间。


myByte := []byte("a","b","c")


for i:=0; i<len(myByte); i++ {

    myByte[i]+=1

}


小唯快跑啊
浏览 106回答 3
3回答

繁花不似锦

分而治之。将你的大数组分成 N 个连续的部分,然后用一个 goroutine 处理每个部分。

慕雪6442864

计时并尝试并行化package addimport (&nbsp; &nbsp; &nbsp; &nbsp; "testing")func BenchmarkSimple(b *testing.B) {&nbsp; &nbsp; &nbsp; &nbsp; // to run use go test -bench=.&nbsp; &nbsp; &nbsp; &nbsp; var array=make([]byte,1000000)&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < b.N; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;addit(&array,1)&nbsp; &nbsp; &nbsp; &nbsp; }}func BenchmarkPara(b *testing.B) {&nbsp; &nbsp; &nbsp; &nbsp; // to run use go test -bench=.&nbsp; &nbsp; &nbsp; &nbsp; var array=make([]byte,1000000)&nbsp; &nbsp; &nbsp; &nbsp; var p1=array[0:250000]&nbsp; &nbsp; &nbsp; &nbsp; var p2=array[250001:500000]&nbsp; &nbsp; &nbsp; &nbsp; var p3=array[500001:750000]&nbsp; &nbsp; &nbsp; &nbsp; var p4=array[750001:999999]&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < b.N; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;go addit(&p1,1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;go addit(&p2,1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;go addit(&p3,1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;go addit(&p4,1)&nbsp; &nbsp; &nbsp; &nbsp; }}func addit(myByte *[]byte, v byte) {for i:=0; i<len(*myByte); i++ {&nbsp; &nbsp; (*myByte)[i]+=v}}这是我在笔记本电脑上看到的。我的笔记本电脑有4核$ go test -bench=.goos: darwingoarch: amd64BenchmarkSimple-4&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1130&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1035976 ns/opBenchmarkPara-4&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 10000&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 559050 ns/opPASSok&nbsp; &nbsp; &nbsp; _/Users/jamandre/wip/add&nbsp; &nbsp; &nbsp; &nbsp; 6.923s对于这样的事情,时间安排并不像看起来那么聪明,请参阅https://www.youtube.com/watch?v=r-TLSBdHe1A&t=46s但请务必把握好时间!四个 goroutine 并没有给 4x 加速,大约 2 x 是相当不错的

蝴蝶不菲

并行化你的代码可能会有所帮助,并行处理是 Go 中的一等公民,因此go指令和goroutines也是如此。SIMD指令还允许对此类计算进行巨大的性能改进。这是一个使用它们的 Go 包。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go