algorithms-go/other/内存拷贝测试/main.go
2021-04-07 14:27:14 +08:00

66 lines
1.3 KiB
Go

package main
//#include <string.h>
import "C"
import (
"bytes"
"fmt"
"math/rand"
"time"
"unsafe"
)
func memcpy(dest, src []byte) int {
n := len(src)
if len(dest) < len(src) {
n = len(dest)
}
if n == 0 {
return 0
}
C.memcpy(unsafe.Pointer(&dest[0]), unsafe.Pointer(&src[0]), C.size_t(n))
return n
}
func genTestData() []byte {
var data = make([]byte, 1024*1024*100)
count := 0
for {
if n, err := rand.Read(data[count:]); err != nil {
panic(err)
} else {
count += n
if count >= 1024*1024*100 {
break
}
}
}
return data
}
func main() {
for i := 0; i < 5; i++ {
fmt.Printf("------------第%d次测试----------------\n", i)
src := genTestData()
var dest1 = make([]byte, len(src))
var dest2 = make([]byte, len(src))
fmt.Println("生成随机测试数据,长度: ", len(src), "开始拷贝:")
start1 := time.Now()
memcpy(dest1, src)
t1 := time.Now().Sub(start1)
if bytes.Equal(src, dest1) && &src != &dest1 {
fmt.Printf("使用C的memcpy函数: %d(%s)\n", len(dest1), t1)
} else {
fmt.Println("使用C的memcpy函数: 拷贝异常")
}
start2 := time.Now()
copy(dest2, src)
t2 := time.Now().Sub(start2)
if bytes.Equal(src, dest2) && &src != &dest2 {
fmt.Printf("使用go的copy函数: %d(%s)\n", len(dest2), t2)
} else {
fmt.Println("使用go的copy函数: 拷贝异常")
}
}
}