我想检查c#或java是否更快,执行冒泡排序功能来排序100000个未排序的记录。
对于C#,我使用此代码进行冒泡排序:
static void sort(int[] table)
{
int n = table.Length;
do
{
for (int i = 0; i < n - 1; i++)
{
if (table[i] > table[i + 1])
{
int tmp = table[i];
table[i] = table[i + 1];
table[i + 1] = tmp;
}
}
n--;
}
while (n > 1);
}
对于java,它几乎是一样的:
static void sort(int[] table)
{
int n = table.length;
do
{
for (int i = 0; i < n - 1; i++)
{
if (table[i] > table[i + 1])
{
int tmp = table[i];
table[i] = table[i + 1];
table[i + 1] = tmp;
}
}
n--;
}
while (n > 1);
}
为了测量执行时间,在C#中我使用了Stopwatch
class:
Stopwatch sw = new Stopwatch();
sw.Start();
sort(arr);
sw.Stop();
我在Java中找不到Stopwatch类,我用这段代码来测量Java中的执行时间:
class ExecutionTimer {
private long start;
private long end;
public ExecutionTimer() {
start = System.nanoTime();
}
public void end() {
end = System.nanoTime();
}
public float duration(){
return (end-start);
}
public void reset() {
start = 0;
end = 0;
}}
我在C#中运行算法5次,在Java中运行5次。 C#中执行时间的平均时间为: 40,13s ,在JAVA中为: 18,44s 。
为什么差异如此之大?是因为我使用StopWatch来测量C#中的时间吗? 我在试验期间关闭了笔记本电脑上的每个程序,浏览器和防病毒软件。
谢谢。
答案 0 :(得分:3)
如果C#运行速度比java慢,我不会感到惊讶,但这里的差异是如此之大,因为你的测试方法不符合要求。
您不能只调用在时钟读数之间进行基准测试的代码。您必须首先通过运行多次来允许代码进行jitted。在基准测试圈中,这被称为&#34; warmup&#34;,对于编译成字节码的语言(在这种情况下可能是MSIL),然后在运行时进行即时编译,这是必要的。 / p>
多少次足以预热?意见不同;我听说你必须运行一次,我听说你必须运行10000次。试着看看你得到了什么。