秒表只有0毫秒

Ghy*_*yro -1 .net c# stopwatch

我有这种类型的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

测试

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();

    }
}
Run Code Online (Sandbox Code Playgroud)

所有图书馆都已连接.

在此输入图像描述

Pan*_*vos 7

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

Time: 00:00:00.0004201ms
Run Code Online (Sandbox Code Playgroud)

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

使用200个项目返回:

Time: 00:00:00.0023507ms
Run Code Online (Sandbox Code Playgroud)

要么

Time: 00:00:00.0050675ms
Run Code Online (Sandbox Code Playgroud)

每次执行都会给出不同的结果,因为quicksort对元素的相对顺序很敏感.线程切换,垃圾收集,其他正在运行的进程也会影响您获得的值.

去2000项目产生的结果大约210-220ms.更一致,但5%的变化仍然太大.

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

更好的想法是使用BenchmarkDotNet并让它运行你的代码足够长的时间,直到它获得稳定的结果.