当前位置: > > > > golang 中的类型转换如何工作?
来源:stackoverflow
2024-04-22 12:09:35
0浏览
收藏
“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《golang 中的类型转换如何工作?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!
问题内容
我的问题陈述是加载和保存带有数字的二进制文件,这些数字可以轻松存储在 uint32/float32
中。这将在磁盘上大约超过 2gb,并且所有内容也都需要在内存中。
我的程序需要大量数学运算,golang标准库函数/方法需要int/float64
参数,我必须将我的数字转换为int/float64
一个简单的基准测试(https://play.golang.org/p/a52-wbo3z34)给出了以下输出:
$: go test -bench=. goos: linux goarch: amd64 pkg: gotrade BenchmarkCast-4 1000 1519964 ns/op BenchmarkNoCast-4 3000 373340 ns/op PASS ok gotrade 2.843s
这清楚地表明类型转换相当昂贵。
int 和 float64 的缺点:
- 它几乎需要双倍的内存
int 和 float64 的优点:
- 避免大量类型转换操作
请建议我一种处理这种情况的方法,我在这里遗漏了什么吗?
如果我们需要通过标准库进行外部计算,我们是否应该始终选择 int
和 float64
?
解决方案
您的逻辑、基准和假设存在一些错误。
至于强制转换,您的结果显示您的 for 循环运行了 1000 次。由于循环 100 万次,这实际上进行了 10 亿次转换操作……还不错。
实际上,我稍微修改了你的代码:
const ( min = float64(math.smallestnonzerofloat32) max = float64(math.maxfloat32) ) func cast(in float64) (out float32, err error) { // we need to guard here, as casting from float64 to float32 looses precision // therefor, we might get out of scope. if in < min { return 0.00, fmt.errorf("%f is smaller than smallest float32 (%f)", in, min) } else if in > max { return 0.00, fmt.errorf("%f is bigger than biggest float32 (%f)", in, max) } return float32(in), nil } // multi64 uses a variadic in parameter, in order to be able // to use the multiplication with arbitrary length. func multi64(in ...float64) (result float32, err error) { // necessary to set it to 1.00, since float64's null value is 0.00... im := float64(1.00) for _, v := range in { im = im * v } // we only need to cast once. // you do want to make the calculation with the original precision and only // want to do the casting once. however, this should not be done here - but in the // caller, as the caller knows on how to deal with special cases. return cast(im) } // multi32 is a rather non-sensical wrapper, since the for loop // could easily be done in the caller. // it is only here for comparison purposes. func multi32(in ...float32) (result float32) { result = 1.00 for _, v := range in { result = result * v } return result } // openfile is here for comparison to show that you can do // a... fantastic metric ton of castings in comparison to io ops. func openfile() error { f, err := os.open("cast.go") if err != nil { return fmt.errorf("error opening file") } defer f.close() br := bufio.newreader(f) if _, _, err := br.readline(); err != nil { return fmt.errorf("error reading line: %s", err) } return nil }
使用以下测试代码
func init() { rand.seed(time.now().utc().unixnano()) } func benchmarkcast(b *testing.b) { b.stoptimer() v := rand.float64() var err error b.resettimer() b.starttimer() for i := 0; i < b.n; i++ { if _, err = cast(v); err != nil { b.fail() } } } func benchmarkmulti32(b *testing.b) { b.stoptimer() vals := make([]float32, 10) for i := 0; i < 10; i++ { vals[i] = rand.float32() * float32(i+1) } b.resettimer() b.starttimer() for i := 0; i < b.n; i++ { multi32(vals...) } } func benchmarkmulti64(b *testing.b) { b.stoptimer() vals := make([]float64, 10) for i := 0; i < 10; i++ { vals[i] = rand.float64() * float64(i+1) } var err error b.resettimer() b.starttimer() for i := 0; i < b.n; i++ { if _, err = multi64(vals...); err != nil { b.log(err) b.fail() } } } func benchmarkopenfile(b *testing.b) { var err error for i := 0; i < b.n; i++ { if err = openfile(); err != nil { b.log(err) b.fail() } } }
你会得到这样的东西
BenchmarkCast-4 1000000000 2.42 ns/op BenchmarkMulti32-4 300000000 5.04 ns/op BenchmarkMulti64-4 200000000 8.19 ns/op BenchmarkOpenFile-4 100000 19591 ns/op
因此,即使使用这种相对愚蠢且未经优化的代码,肇事者仍然是 openfile 基准测试。
现在,让我们正确看待这一点。 19,562ns 等于 0,019562 毫秒。一般人可以感知到的延迟约为 20 毫秒。因此,即使是 100,000(“十万”)文件打开、行读取和文件关闭也比人类感知的速度快 1000 倍。
与此相比,转换速度要快几个数量级 – 所以你可以随意转换,你的瓶颈将是 i/o。
编辑
这留下了一个问题,为什么您不首先将值导入为 float64?
理论要掌握,实操不能落!以上关于《golang 中的类型转换如何工作?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注公众号吧!