一百万次双整数转换的执行时间与空循环相同

问题描述 投票:0回答:1

我正在编写一个具有很多int-double-int转换的高性能组件,所以我需要知道它们之间的执行时间。

static double ToDouble(int val) => (double)val;

static int ToInt(double val) => (int)val;

static void Main(string[] args) {
    const int TIMES = 1000_0000;
    Console.ReadLine();

    var t_0 = Stopwatch.GetTimestamp();
    for (int i = 0; i < TIMES; i++) {
        var val = ToInt(ToDouble(i));
    }
    var t_1 = Stopwatch.GetTimestamp();
    Console.WriteLine((t_1 - t_0) * 100_0000L / Stopwatch.Frequency); // 4002 Microseconds


    var t_2 = Stopwatch.GetTimestamp();
    for (int i = 0; i < TIMES; i++) {

    }
    var t_3 = Stopwatch.GetTimestamp();
    Console.WriteLine((t_3 - t_2) * 100_0000L / Stopwatch.Frequency); // 3997 Microseconds


    Console.ReadLine();
}

我发现int-double-int转换是如此之快,以至于执行时间可与空循环媲美。

我认为第一个循环中的代码根本不执行,编译器将其优化为空循环,是吗?

c# .net
1个回答
0
投票

您应该使用StopWatch.Start和Stop然后已过去!

const int TIMES = 100_000_000;

var chrono = new Stopwatch();

chrono.Start();
for ( int i = 0; i < TIMES; i++ )
{
  var val = ToInt(ToDouble(i));
}
chrono.Stop();
Console.WriteLine(chrono.ElapsedMilliseconds.ToString());

chrono.Start();
for ( int i = 0; i < TIMES; i++ )
{
}
chrono.Stop();
Console.WriteLine(chrono.ElapsedMilliseconds.ToString());

输出:

776
1005
© www.soinside.com 2019 - 2024. All rights reserved.