【问题标题】:Stopwatch has only 0ms [closed]秒表只有 0ms [关闭]
【发布时间】:2019-03-07 07:43:14
【问题描述】:

我有 QuickSort 和 Test Class 用于这种排序。 秒表不工作,总是 0ms。

任务是实现指定的算法——将程序设计为控制台应用程序。我需要根据源数据的长度估计算法的执行时间。

快速排序

public static void Sorting(int[] array, int first, int last)
{
    int x = array[(last - first) / 2 + first];
    int temp;

    int i = first;
    int j = last;

    while (i <= j)
    {
        while (array[i] < x && i <= last) ++i;
        while (array[j] > x && j >= first) --j;

        if (i<=j)
        {
            temp = array[i];
            array[i] = array[j];
            array[j] = temp;
            ++i;
            --j;
        }
    }

    if (j > first)
    {
        Sorting(array, first, j);
    }

    if (i < last)
    {
        Sorting(array, i, last);
    }
}

测试

class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopwatch = new Stopwatch();
        int[] array = new int[20];

        Random random = new Random();

        for (int i=0; i<array.Length; i++)
        {
            array[i] = random.Next(1, 20);
        }

        Console.WriteLine("Sorting...");

        stopwatch.Start();

        for (int i=0; i < array.Length; i++)
        {
            QuickSort.Sorting(array, 0, array.Length - 1);
        }           

        stopwatch.Stop();            

        Console.WriteLine("\nCheck:");
        foreach (int x in array)
        {
            Console.WriteLine(x + "");
        }
        Console.WriteLine("Time: {0}ms", stopwatch.ElapsedMilliseconds);
        stopwatch.Reset();

        Console.ReadKey();

    }
}

所有库都已连接。

【问题讨论】:

  • 您是否考虑过您的代码执行时间不到 1 毫秒?
  • 对于基准测试考虑使用 BenchmarkDotNet:github.com/dotnet/BenchmarkDotNet
  • 秒表是非常原始的基准

标签: c# .net stopwatch


【解决方案1】:

只要您的输入只有 20 个元素长,几乎不需要时间对其进行排序。请尝试使用更大的输入或尝试查找刻度而不是 ms。

【讨论】:

  • 我必须使用更大的数组吗?
  • 更大。尝试类似 100000 个元素。
【解决方案2】:

如果你使用 Elapsed 而不是 ElapsedMilliseconds 你会得到类似的东西:

Time: 00:00:00.0004201ms

对如此小的数组进行排序甚至不需要 1 毫秒。事实上,我怀疑写入控制台或可能的线程切换会更多地影响时间。

使用 200 项返回:

Time: 00:00:00.0023507ms

或者

Time: 00:00:00.0050675ms

每次执行都会给出不同的结果,因为快速排序对元素的相对顺序很敏感。线程切换、垃圾回收、其他正在运行的进程也会影响你得到的值。

搜索 2000 个项目会在 210-220 毫秒左右产生结果。更一致,但 5% 的变化仍然太大。

如果您真的想要对您的代码进行基准测试,至少您需要对其进行多次测试并对结果进行平均。

一个更好的主意是使用 BenchmarkDotNet 并让它运行您的代码足够长的时间,直到它获得稳定的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 2015-10-09
    • 2020-11-26
    • 2012-03-20
    • 2017-07-30
    • 1970-01-01
    • 2011-06-13
    相关资源
    最近更新 更多