为什么运行时在数组搜索方案C#中有所不同

时间:2014-01-28 17:25:18

标签: c# performance-testing performancecounter

我目前正在测试数组中数字搜索的平均时间。我正在测试二进制搜索,顺序索引搜索和自定义函数。使用随机长度和随机值初始化数组。测试时我发现了两件事......

1。)在下面的程序循环中,我的自定义函数比二进制搜索快大约5-7倍,具体取决于数组大小。通常,当阵列较大时,它会快得多,这是目标。

static void Main(string[] args)
{
    int[] randomarray = CreateRandomArray();
    for(int loops = 0;loops < totalsamples;loops ++)
    {
        int tosearchfor = CreateRandomNumber();
        RecordMyCustomFunctionTime(randomarray,tosearchfor);
        RecordBinarySearchTime(randomarray,tosearchfor);
        RecordSequentialSearchTime(randomarray,tosearchfor);
    }
    CalculateAndDisplayAverages();
}

2。)在下面的程序循环中,我的自定义功能大约快2-3倍,具体取决于阵列大小。二进制搜索和顺序搜索与之前大致相同

static void Main(string[] args)
{
    for(int loops = 0;loops < totalsamples;loops ++)
    {
        int[] randomarray = CreateRandomArray();
        int tosearchfor = CreateRandomNumber();
        RecordMyCustomFunctionTime(randomarray,tosearchfor);
        RecordBinarySearchTime(randomarray,tosearchfor);
        RecordSequentialSearchTime(randomarray,tosearchfor);
    }
    CalculateAndDisplayAverages();
}

我也用一组数组大小和相同的结果对它进行了测试。我正在使用秒表类,它报告我有一个高分辨率的性能计数器。为什么这样的差异仅取决于数组的创建位置以及我的函数?

0 个答案:

没有答案