秒表只有0毫秒

时间:2018-10-02 07:42:54

标签: c# .net 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);
    }
}

测试

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

    }
}

所有库都已连接。

enter image description here

2 个答案:

答案 0 :(得分:7)

如果您使用Elapsed而不是ElapsedMilliseconds,将会得到类似的信息:

Time: 00:00:00.0004201ms

排序这样一个很小的数组甚至不需要1毫秒。实际上,我怀疑通过写入控制台或可能的线程切换会更多地影响时间。

使用200项将返回:

Time: 00:00:00.0023507ms

Time: 00:00:00.0050675ms

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

输入2000个项目会在210-220毫秒左右产生结果。一致性更高,但5%的差异仍然太大。

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

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

答案 1 :(得分:2)

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