地鼠们你好?
在这篇博文中,我将向您展示如何使用 #golang 测试包中内置的出色工具。您将如何测试一段代码或函数的性能?使用基准测试。
我们走吧。
对于此测试,我将使用经典的斐波那契数列或斐波那契数列,它由以下因素确定:
if (x <p>这个序列很重要,因为它也出现在数学和自然的多个部分中,如下所示:</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172554306490300.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Benchmark with Golang"></p> <p>有多种方法可以实现此代码,我将选择两种方法进行基准测试:计算它的递归方法和迭代方法。这些函数的主要目标是提供<em>位置</em>并返回该位置的斐波那契数。</p> <h2> 递归法 </h2> <pre class="brush:php;toolbar:false">// main.go func fibRecursive(n int) int { if n <h2> 迭代法 </h2> <pre class="brush:php;toolbar:false">// main.go func fibIterative(position uint) uint { slc := make([]uint, position) slc[0] = 1 slc[1] = 1 if position <p>这些方法并未经过优化,但即使对于少数情况,测试结果也有显着差异。您将在测试中看到这一点。要跟随代码进行操作,您可以点击此处。</p> <p>现在,对于<strong>基准测试</strong>测试,让我们在 _main_test.go 文件中编写一些测试。使用 Golang 的 <strong>benchmark</strong> 文档,您可以创建要测试的函数,如下所示:<br> </p> <pre class="brush:php;toolbar:false">// main_test.go // The key is to start every function you want to benchmark with the keyword Benchmark and use b *testing.B instead of t *testing.T as input func BenchmarkFibIterative(b *testing.B) { // Use this for-loop to ensure the code will behave correctly. // Now, you can put the function or piece of code you want to test for i := 0; i <blockquote> <p>在继续之前问一个问题:哪个更快?</p> </blockquote> <p>让我们对一个较小的数字 (10) 和一个稍大的数字 (80) 运行测试。要运行<strong>基准</strong>测试,您只需运行命令:</p> <p>go test -bench=函数名称</p> <p>如果您想了解更多有关此命令的信息,请查看此处。</p> <p><strong>第一次测试:position=10</strong><br> </p> <pre class="brush:php;toolbar:false">//(fibIterative) Results: cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz BenchmarkFibIterative-8 24491042 42.50 ns/op PASS ok playground 1.651s
让我们借助这张图来分析一下:
根据图像,我们有8个核心用于测试,没有时间限制(它将运行到完成)。花了1.651s完成任务。
==== Extra ==== We got 24,491,042 iterations (computations), and each iteration (op) took 42.50 ns. Doing some math, we can calculate how much time one op took: 42.50 ns/op with 1 ns = 1/1,000,000,000 s op ≈ 2.35270590588e-12 s ==== Extra ====
这是一个很好的结果。让我们检查一下位置 10 的递归函数:
// Results BenchmarkFibRecursive-8 6035011 187.8 ns/op PASS ok playground 1.882s
我们可以看到,完成任务花了1.882s。
迭代函数以几十分之一的优势获胜。让我们再尝试一项测试:
位置 50
// Results for the Iterative Function cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz BenchmarkFibIterative-8 27896118 45.37 ns/op PASS ok playground 2.876s // Results for the Recursive Function cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz BenchmarkFibRecursive-8 6365198 186.3 ns/op PASS ok playground 1.918s
哇!现在递归函数更快了?
让我们以稍微大一点的数字结束。
位置 80
// Results for the Iterative Function cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz BenchmarkFibIterative-8 5102344 229.5 ns/op PASS ok playground 1.933s // Results for the Recursive Function // My poor PC couldn’t handle it, so I had to reduce the position to 50 just to get some results printed. cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz BenchmarkFibRecursive-8 1 44319299474 ns/op PASS ok playground 44.951s
差异是巨大的。对于位置 80,迭代方法大约需要 2 秒。对于位置 50,递归函数花费了大约 45 秒。这证明了当您的 Golang 项目开始变慢时对代码进行基准测试的重要性。
结论
如果您的生产代码运行缓慢或不可预测地变慢,您可以使用此技术,结合 pprof 或内置测试包中的其他工具来识别和测试代码的执行位置不好以及如何优化它。
旁注:并非所有看起来漂亮的代码都具有更高的性能。
额外运动
你能找到更好的方法来改进递归函数吗? (提示:使用动态规划)。本文解释了为什么对于一些小数字,递归策略更好。
以上是使用 Golang 进行基准测试的详细内容。更多信息请关注PHP中文网其他相关文章!

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

go'serrorhandlingurturnserrorsasvalues,与Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

AnefactiveInterfaceoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForeabStractionTosWapImplementations withCallingCallingCode.3)

集中式错误处理在Go语言中可以提升代码的可读性和可维护性。其实现方式和优势包括:1.将错误处理逻辑从业务逻辑中分离,简化代码。2.通过集中处理错误,确保错误处理的一致性。3.使用defer和recover来捕获和处理panic,增强程序健壮性。

Ingo,替代词Inivuntionsionializatializatializationfunctionsandsingletons.1)customInitializationfunctions hallowexpliticpliticpliticconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconcontirization curssementializatizatupsetups.2)单次固定元素限制ininconinconcurrent

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Go语言的错误处理通过errors.Is和errors.As函数变得更加灵活和可读。1.errors.Is用于检查错误是否与指定错误相同,适用于错误链的处理。2.errors.As不仅能检查错误类型,还能将错误转换为具体类型,方便提取错误信息。使用这些函数可以简化错误处理逻辑,但需注意错误链的正确传递和避免过度依赖以防代码复杂化。

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

禅工作室 13.0.1
功能强大的PHP集成开发环境

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

SublimeText3 Linux新版
SublimeText3 Linux最新版

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具