golang 中的类型转换如何工作?
“纵有疾风来,人生不言弃”,这句话送给正在学习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 中的类型转换如何工作?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
华为新款磁吸移动电源通过3C认证,预计将与Pura 70新手机壳同步推出
- 上一篇
- 华为新款磁吸移动电源通过3C认证,预计将与Pura 70新手机壳同步推出
- 下一篇
- Mac双系统管理员账户?
-
- Golang · Go问答 | 5小时前 |
- Go cgo.Handle 管理 Go 值跨语言传递
- 403浏览 收藏
-
- Golang · Go问答 | 6小时前 | CGO · 内存管理 · Go问答 · Go CGO unsafe.Pointer cgo.Handle runtime.Pinner
- Go cgo 指针规则导致 panic 的边界定位
- 223浏览 收藏
-
- Golang · Go问答 | 6小时前 | go ·
- Go GOMAXPROCS 变化对并发吞吐的影响
- 417浏览 收藏
-
- Golang · Go问答 | 7小时前 | go · pprof · Go alloc_space inuse_space heap profile
- Go heap profile inuse_space 与 alloc_space 的选择
- 350浏览 收藏
-
- Golang · Go问答 | 8小时前 | go · 性能排查 ·
- Go runtime/trace 观察阻塞区域的阅读方式
- 283浏览 收藏
-
- Golang · Go问答 | 8小时前 | Go问答 · Go pprof 性能剖析 goroutine泄漏 并发排查
- Go pprof goroutine 泄漏剖析的采样方法
- 104浏览 收藏
-
- Golang · Go问答 | 8小时前 | 垃圾回收 · 资源管理 · Go问答 · Go 资源释放 AddCleanup close SetFinalizer
- Go SetFinalizer 不适合资源关闭的替代方案
- 439浏览 收藏
-
- Golang · Go问答 | 9小时前 |
- Go runtime.KeepAlive 防止句柄过早回收
- 489浏览 收藏
-
- Golang · Go问答 | 9小时前 |
- Go Signal Stop 与退出流程的竞态处理
- 168浏览 收藏
-
- Golang · Go问答 | 2天前 |
- Go ColumnTypes 推断动态查询字段的安全用法
- 319浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 291次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 344次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 347次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 309次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 131次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览
-
- Go sql.Tx提交成功前读取结果导致事务边界混乱的修复方法
- 2026-09-20 501浏览
-
- Go select 用 time.After 做超时有什么资源代价
- 2026-09-10 501浏览
