我正在编写C ++和GoLang之间的性能比较以获取数据以执行统计分析,我创建了一个Python脚本来获取所有数据并自行执行这两个程序。使用C ++我没有问题,并且执行正常,但是我得到了这个错误:
panic: runtime error: index out of range
goroutine 1 [running]:
runtime.panic(0x44d600, 0x4b9897)
/usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
main.merge(0xc210047000, 0x9, 0x10, 0x8, 0x8, ...)
/windows/DATA/FIB/PE/B7_PLSpeed/nlogn.go:13 +0x22c
main.mergesort(0xc210047000, 0x9, 0x10, 0x8, 0x9)
/windows/DATA/FIB/PE/B7_PLSpeed/nlogn.go:43 +0xec
main.mergesort(0xc210047000, 0x9, 0x10, 0x5, 0x9)
/windows/DATA/FIB/PE/B7_PLSpeed/nlogn.go:42 +0xac
main.mergesort(0xc210047000, 0x9, 0x10, 0x0, 0x9)
/windows/DATA/FIB/PE/B7_PLSpeed/nlogn.go:42 +0xac
main.main()
/windows/DATA/FIB/PE/B7_PLSpeed/nlogn.go:54 +0x1c1
如果有人可以帮助我,我会非常高兴! 我将留下我的Python脚本和Go源代码。
的Python:
import time
import random
from subprocess import call
from sys import argv
def usage():
print("Usage: " + argv[0] + " <Binary1> <Binary2> <n elements> <#executions>")
if __name__ == '__main__':
if len(argv) != 5:
usage()
else:
program1 = argv[1]
program2 = argv[2]
n = int(argv[3])
executions = int(argv[4])
for x in range(0, executions):
command = ['']
# 32-bit range vector(n) random generator
for y in range(0, n-1):
command.append(str(random.randint(-2147473648, 2147473647)))
if(random.choice((True, False))):
program1, program2 = program2, program1
# Program1
command[0] = './' + program1
pre = time.time()
call(command)
post = time.time()
f = open(program1 + ' - ' + str(n), 'a')
f.write(str(post-pre) + "ms\n")
f.close
# Program2
command[0] = './' + program2
pre = time.time()
call(command)
post = time.time()
f = open(program2 + ' - ' + str(n), 'a')
f.write(str(post-pre) + "ms\n")
f.close
转到:
package main
import "strconv"
import "os"
func merge(v []int, e int, m int, d int) {
size := d-e+1
B := make([]int, size)
i := e
j := m + 1
k := 0
for i <= m && j <= d {
if v[i] <= v[j] {
B[k] = v[i]
k++
i++
} else {
B[k] = v[j]
k++
j++
}
}
for i <= m {
B[k] = v[i]
k++
i++
}
for j <= d {
B[k] = v[j]
k++
j++
}
for k := 0; k <= d-e; k++ {
v[e+k] = B[k]
}
}
func mergesort(v []int, e int, d int) {
if e < d {
m := (e+d)/2
mergesort(v, e, m)
mergesort(v, m+1, d)
merge(v, e, m, d)
}
}
func main() {
v := make([]int, 0)
args := os.Args
for i := 1; i < len(args); i++ {
f,_ := strconv.Atoi(os.Args[i])
v = append(v, f)
}
mergesort(v, 0, len(args) - 1)
}
答案 0 :(得分:4)
问题不在你的Python中,因为Go程序在没有从Python调用的情况下会得到相同的错误。在main
func中,您正在创建一个名为v
的切片,从参数位置1
开始,因此不包括该程序的名称:
for i := 1; i < len(args); i++ {
f,_ := strconv.Atoi(os.Args[i])
v = append(v, f)
}
但是,您提供mergesort
args
的长度,而不是v
的长度,因此它是一个一个一个错误,因为它和&#1}} #39;被告知v
还有1个元素,而不是实际元素。在该行下方,程序尝试访问超出切片末尾的v
元素:
mergesort(v, 0, len(args) - 1)
请在主要功能中尝试mergesort(v, 0, len(v) - 1)
。
答案 1 :(得分:-3)
尝试更改:
call(command, shell=True)
到
hours_3[23]