Print elapsed time with constant format?

xuanbao · · 349 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p><strong>Update below</strong></p> <p>I think an example is easier to understand that my bad English explanation, so here is my code:</p> <pre><code>start := time.Now() //MyCode end := time.Now() elapsed := end.Sub(start) fmt.Println(&#34;Elapsed&#34;, &#34;:&#34;, elapsed) </code></pre> <p>This is the output I get when I execute the code repeatedly:</p> <blockquote> <p>myExecutable.exe</p> </blockquote> <p>Elapsed : 996.4µs</p> <blockquote> <p>myExecutable.exe</p> </blockquote> <p>Elapsed : 0s</p> <blockquote> <p>myExecutable.exe</p> </blockquote> <p>Elapsed : 998µs</p> <blockquote> <p>myExecutable.exe</p> </blockquote> <p>Elapsed : 1.0031ms</p> <p>How can I do it so that it always gives me the time in the same format? (Always µs, or always ms, but not have it sometime print 0s, that gives no valuable information).</p> <p>Thank you all for your patience.</p> <p><strong>Update: This is what I got right now:</strong></p> <pre><code>start := time.Now() //MyCode ns := time.Since(start) fmt.Println(&#34;Elapsed ns&#34;, &#34;:&#34;, ns.Nanoseconds()) </code></pre> <p>It keeps printing 0 sometimes, and there&#39;s no way my code takes 0ns to execute.</p> <blockquote> <p>myExecutable.exe</p> </blockquote> <p>Elapsed ns : 1002200</p> <blockquote> <p>myExecutable.exe</p> </blockquote> <p>Elapsed ns : 0</p> <blockquote> <p>myExecutable.exe</p> </blockquote> <p>Elapsed ns : 970100</p> <hr/>**评论:**<br/><br/>qu33ksilver: <pre><p>Maybe this is what you want - <a href="https://golang.org/pkg/time/#Duration.Nanoseconds" rel="nofollow">https://golang.org/pkg/time/#Duration.Nanoseconds</a> ?</p></pre>muzska: <pre><p>Thanks for the suggestion but not really, according to that example that function is used to convert a string to time:</p> <pre><code>ns, _ := time.ParseDuration(&#34;1000ns&#34;) fmt.Printf(&#34;one microsecond has %d nanoseconds.&#34;, ns.Nanoseconds()) </code></pre> <p>I just want to measure time, not convert any string to time.</p> <p><em>Update</em>: Ok this seems to work:</p> <pre><code>start := time.Now() //MyCode ns := time.Since(start) fmt.Println(&#34;Elapsed ns&#34;, &#34;:&#34;, ns.Nanoseconds()) </code></pre> <p>Thanks for your help</p> <p><em>Update 2</em>: It still gives random 0 values sometimes. </p></pre>drvd: <pre><p>Convert it to a string manually. time.Durations are nanoseconds, just decide how you&#39;d like them to be displayed and do it.</p></pre>muzska: <pre><p>First of all, thanks for your comment.</p> <p>That&#39;s what I am currently doing, but it sometimes displays 0<em>ns</em> elapsed time, which is obviously imposible.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

349 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传