【问题标题】:In VB 2008, why does manipulation of shorts take longer than integers?在 VB 2008 中,为什么短裤操作比整数需要更长的时间?
【发布时间】:2010-12-31 12:24:31
【问题描述】:

在这个例子中:

Sub Button1_Click(sender As Object, ByVal e As EventArgs) Handles Button1.Click
    Dim stopwatch1, stopwatch2 As New Stopwatch : Dim EndLoop As ULong = 10000

    stopwatch1.Start()
    For cnt As ULong = 1 To EndLoop
        Dim Number1 As UInt32
        For Number1 = 1 To 20000
            Dim Number2 As UInt32 = 0
            Number2 += 1
        Next
    Next
    stopwatch1.Stop()

    stopwatch2.Start()
    For cnt As ULong = 1 To EndLoop
        Dim Number1 As UShort
        For Number1 = 1 To 20000
            Dim Number2 As UShort = 0
            Number2 += 1
        Next
    Next
    stopwatch2.Stop()

    Label1.Text = "UInt32: " & stopwatch1.ElapsedMilliseconds
    Label2.Text = "UShort: " & stopwatch2.ElapsedMilliseconds
End Sub

UInt32 循环我一直得到大约 950 毫秒,UShort 循环大约 1900 毫秒。如果我将 UShort 更改为 Short,我也会得到大约 1900 毫秒。

另外,我可以将第二个循环更改为:

stopwatch2.Start()
For cnt As ULong = 1 To EndLoop
    Dim Number1 As Integer
    For Number1 = 1 To 20000
        Dim Number2 As Integer = 0
        Number2 += 1
    Next
Next
stopwatch2.Stop()

整数循环将始终为 660 毫秒,而 UInt32 循环为 950 毫秒。

与 Short、UShort 和 UInt32 相比,整数是更快的数据类型吗?如果有,为什么?

【问题讨论】:

  • 尝试等待真正创建第二个秒表,直到第一次上厕所

标签: visual-studio-2008 optimization unsigned short


【解决方案1】:

我敢打赌,这是因为您机器上的自然字长是 32 位,而执行 16 位操作实际上会给系统带来更大的压力来剪切和屏蔽位。

如果您在 64 位处理器上进行测试,则 Int64 可能会比 Int32 获得更好的结果...

此外,在 .NET 中,所有整数(最多 32 位)算术都会自动向上转换为 int,因此当您将结果分配回 short 变量时,会导致额外的转换步骤。 uint 也是如此。

【讨论】:

  • 我认为你是对的。我在 Win 7 64 位的四核上运行。我将程序更改为针对 x86 进行编译,它在大约 250 毫秒内运行了 Int32 循环。我创建了第二个循环 Int64,它在 x86 和 x64 上都以大约 650 毫秒的时间编译。从 x86 更改为 x64 之间的唯一区别是,与 x86 上的 250 毫秒相比,它使 Int32 操作花费了大约 660 毫秒的时间。所以知道我认为你是正确的,因为我敢打赌它在 x86 上对 Int16 做同样的事情,就像 x64 对 Int32 做的一样。
  • 很高兴我提供了一些见解,如果您检查一下,您可能会发现我的最后一段也是正确的:)
  • 哈哈,我今天的代表上限,随你喜欢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
相关资源
最近更新 更多