【发布时间】:2017-11-06 11:37:33
【问题描述】:
我想通过执行冒泡排序功能对 100000 条未排序的记录进行排序来检查 c# 或 java 是否更快。
对于 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 类:
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# 中测量时间吗? 在测试期间,我关闭了笔记本电脑上的所有程序、浏览器和防病毒软件。
谢谢。
【问题讨论】:
-
你是否运行了带有调试器的 C# 版本?
-
你是否在发布模式下编译了 C# 代码?
-
我用调试模式运行它。
-
运行调试版本会很慢。在附加调试器的情况下运行(即在 Visual Studio 中按 F5)会非常慢。运行不带调试器的发布版本(在 Visual Studio 中按 Ctrl+F5,或选择“不带调试器运行”)。如果您正在运行调试版本或附加了调试器,那么您的时间将会大大缩短。
标签: java c# sorting optimization