时间例程中奇怪的输出 [英] Weird output in time routines

查看:70
本文介绍了时间例程中奇怪的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我得到一些非常意外的输出时,我正在创建一些非常基本的时间例程来进行一些测试.

我的代码是一个简单的控制台应用程序:

I was creating some very basic time routines to do some testing when I ended up with some very unexpected output.

My code was a simple console app:

Imports System.Threading

Module Module1
    Sub Main()
        Dim StartTime As DateTime
        Dim EndTime As DateTime

        For i As Integer = 1 To 10
            StartTime = DateTime.Now
            Thread.Sleep(5)
            EndTime = DateTime.Now
            Console.WriteLine(EndTime.Millisecond - StartTime.Millisecond)
        Next
        Console.ReadLine()
    End Sub
End Module



但输出是:

5
5
5
-995
5
5
5
5
5
5

预期会是5英寸(甚至偶尔有6英寸)... -995不是.

谁能解释导致系统将其作为输出生成的原因?



but the output was:

5
5
5
-995
5
5
5
5
5
5

The 5''s (and even the occassional 6) were expected ... the -995 wasn''t.

Can anyone explain what would have caused the system to generate that as an output?

Thanks.

推荐答案

因为有时StartTime.Millisecond = 995,而EndTime.Millisecond为0.
您真正想要做的是:

Because sometimes, the StartTime.Millisecond = 995, and the EndTime.Millisecond is 0.

What you REALLY want to do is this:

Console.WriteLine((EndTime - StartTime).TotalMilliseconds)


我想我是在点击Submit之后才发现的.

因为我只是在毫秒部分进行数学运算,所以有时将开始时间设为.995,然后将结束时间换成.000(或.995-.999之间的变化)...从而给出否定结果.

有趣.
I think I figured it out just after hitting submit.

Because I''m only doing the math on the millisecond portion it will sometimes have .995 as the start time and then wrap to .000 for the end time (or variations between .995 - .999) ... and thus give the negative result.

Interesting.


这篇关于时间例程中奇怪的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆