<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("Elapsed", ":", 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("Elapsed ns", ":", ns.Nanoseconds())
</code></pre>
<p>It keeps printing 0 sometimes, and there'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("1000ns")
fmt.Printf("one microsecond has %d nanoseconds.", 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("Elapsed ns", ":", 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'd like them to be displayed and do it.</p></pre>muzska: <pre><p>First of all, thanks for your comment.</p>
<p>That'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
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传