编辑:我会尝试更好地指出我的问题。我不是在询问如何衡量性能或任何事情或如何编写算法。我试图将镜像 java应用程序的源代码转换为C#。 java代码的运行速度比C#代码快1.3到2.0倍。那为什么会那样?我在移植代码时犯了错误吗? java中的ExecutorService的线程是否与c#任务相同?为什么甚至java单线程比c#multithreaded更快(java multithreaded是最快的)?
出于测试目的(回到语言),我用Java编写了一个伪暴力应用程序,然后将其移植到C#。我试图尽可能地改变,以便两个源在语义上保持相同。我知道这些代码片段并不完美,请不要尝试纠正它背后的算法,因为这与问题无关。
问题: 因此,当我连续运行两个应用程序然后比较输出时,Java在每次尝试中都会更快,而Java单线程几乎与C#multithreaded一样快或更快。我想知道为什么它是这样的,也许我在C#版本的代码中做错了(如果有的话)。关于致命编码错误的任何暗示? 另外,在Windows XP配置中,C#multithreaded比C#单线程慢(这怎么可能?)。
尝试了两种配置:
1)
Windows 7 x64
i7 cpu, 8 cores ( 4 physical cores + Hyperthreading )
.Net 4.0 and jdk 7
2)
Windows XP x86
Atom N270, 2 cores ( 1 physical core + Hyperthreading )
.Net 4.0 and jdk 7
我正在发布代码,以便您自己测试。
Java代码:
Entry.java
package test;
import java.util.Scanner;
public class Entry
{
public static void main(String[] args)
{
System.out.print("Type password to be cracked: ");
String input = new Scanner(System.in).nextLine();
PasswordCracker cracker = new PasswordCracker();
System.out.println("Multithreaded");
cracker.runMulti(input);
cracker = new PasswordCracker();
System.out.println("Singlethreaded");
cracker.runSingle(input);
System.out.println("Finished...");
}
}
PasswordCracker.java
package test;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class PasswordCracker
{
String passwordToCrack;
public boolean passwordFound;
int min;
int max;
StringBuilder crackedPassword;
public void prepare(String text)
{
passwordToCrack = text;
passwordFound = false;
min = 32;
max = 126;
crackedPassword = new StringBuilder();
crackedPassword.append((char) (min - 1));
}
public void result()
{
System.out.println("Cracked Password is: " + crackedPassword.toString());
}
public void incrementString(StringBuilder text, int min, int max)
{
text.setCharAt(0, (char) ((int) text.charAt(0) + 1));
for (int i = 0; i < text.length(); i++)
{
if (text.charAt(i) > (char) max)
{
text.setCharAt(i, (char) min);
if (text.length() == i + 1)
{
text.append((char) min);
}
else
{
text.setCharAt(i + 1, (char) ((int) text.charAt(i + 1) + 1));
}
}
}
}
public void runMulti(String text)
{
prepare(text);
double time = System.nanoTime();
doItMulti();
time = System.nanoTime() - time;
System.out.println(time / (1000000000));
result();
}
public void runSingle(String text)
{
prepare(text);
double time = System.nanoTime();
doItSingle();
time = System.nanoTime() - time;
System.out.println(time / (1000000000));
result();
}
public void doItSingle()
{
while (passwordFound == false)
{
incrementString(crackedPassword, min, max);
passwordFound = crackedPassword.toString().equals(passwordToCrack);
}
}
public void doItMulti()
{
int cores = Runtime.getRuntime().availableProcessors();
ArrayList<Future<?>> tasks = new ArrayList<Future<?>>(cores);
ExecutorService executor = Executors.newFixedThreadPool(cores);
final long step = 2000;
for (long i = 0; i < Long.MAX_VALUE; i += step)
{
while(tasks.size() > cores)
{
for(int w = 0; w < tasks.size();w++)
{
if(tasks.get(w).isDone())
{
tasks.remove(w);
break;
}
}
try
{
Thread.sleep(0);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
{
final long j = i;
if (passwordFound == false)
{
tasks.add(executor.submit(new Runnable()
{
public void run()
{
long border = j + step;
StringBuilder toCrack = new StringBuilder(10);
toCrack.append(constructString3(j, min, max));
for (long k = j; k < border; k++)
{
incrementString(toCrack, min, max);
boolean found = toCrack.toString().equals(passwordToCrack);
if (found)
{
crackedPassword = toCrack;
passwordFound = found;
break;
}
}
}
}));
}
else
{
break;
}
}
}
executor.shutdownNow();
}
public String constructString3(long number, long min, long max)
{
StringBuilder text = new StringBuilder();
if (number > Long.MAX_VALUE - min)
{
number = Long.MAX_VALUE - min;
}
ArrayList<Long> vector = new ArrayList<Long>(10);
vector.add(min - 1 + number);
long range = max - min + 1;
boolean nextLetter = false;
for (int i = 0; i < vector.size(); i++)
{
long nextLetterCounter = 0;
while (vector.get(i) > max)
{
nextLetter = true;
long multiplicator = Math.abs(vector.get(i) / range);
if ((vector.get(i) - (multiplicator * range)) < min)
{
multiplicator -= 1;
}
vector.set(i, vector.get(i) - (multiplicator * range));
nextLetterCounter += multiplicator;
}
if (nextLetter)
{
vector.add((long) (min + nextLetterCounter - 1));
nextLetter = false;
}
text.append((char) vector.get(i).intValue());
}
return text.toString();
}
}
和C#代码:
Entry.cs
using System;
namespace PasswordCracker
{
class Entry
{
public static void Main(String[] args)
{
Console.Out.WriteLine("Type password to be cracked:");
String input = Console.In.ReadLine();
PasswordCracker cracker = new PasswordCracker();
Console.Out.WriteLine("Multithreaded");
cracker.runMulti(input);
cracker = new PasswordCracker();
Console.Out.WriteLine("Singlethreaded");
cracker.runSingle(input);
Console.Out.WriteLine("Finished...");
Console.ReadKey();
}
}
}
PasswordCracker.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
namespace PasswordCracker
{
public class PasswordCracker
{
String passwordToCrack;
public bool passwordFound;
int min;
int max;
StringBuilder crackedPassword;
public void prepare(String text)
{
passwordToCrack = text;
passwordFound = false;
min = 32;
max = 126;
crackedPassword = new StringBuilder();
crackedPassword.Append((char)(min - 1));
}
public void result()
{
Console.Out.WriteLine("Cracked Password is: " + crackedPassword.ToString());
}
public void incrementString(StringBuilder text, int min, int max)
{
text[0] = (char)((text[0]) + 1);
for (int i = 0; i < text.Length; i++)
{
if (text[i] > (char)(max))
{
text[i] = (char)(min);
if (text.Length == i + 1)
{
text.Append((char)(min));
}
else
{
text[i + 1] = (char)((text[i + 1]) + 1);
}
}
}
}
public void runMulti(String text)
{
prepare(text);
Stopwatch time = new Stopwatch();
time.Start();
doItMulti();
Console.Out.WriteLine(time.Elapsed.TotalSeconds);
result();
}
public void runSingle(String text)
{
prepare(text);
Stopwatch time = new Stopwatch();
time.Start();
doItSingle();
Console.Out.WriteLine(time.Elapsed.TotalSeconds);
result();
}
public void doItSingle()
{
while (passwordFound == false)
{
incrementString(crackedPassword, min, max);
passwordFound = crackedPassword.ToString().Equals(passwordToCrack);
}
}
public void doItMulti()
{
int cores = Environment.ProcessorCount;
long step = 2000;
List<Task> tasks = new List<Task>(cores);
for (long i = 0; i < long.MaxValue; i += step)
{
while (tasks.Count > cores)
{
for (int a = 0; a < tasks.Count;a++)
{
if (tasks[a].IsCompleted)
{
tasks.RemoveAt(a);
break;
}
}
Thread.Sleep(0);
}
{
long j = i;
if (passwordFound == false)
{
tasks.Add(Task.Factory.StartNew(delegate
{
long border = j + step;
StringBuilder toCrack = new StringBuilder(10);
toCrack.Append(constructString3(j, min, max));
for (long k = j; k < border; k++)
{
incrementString(toCrack, min, max);
bool found = toCrack.ToString().Equals(passwordToCrack);
if (found)
{
crackedPassword = toCrack;
passwordFound = found;
break;
}
}
}));
}
else
{
break;
}
}
}
}
public String constructString3(long number, long min, long max)
{
StringBuilder text = new StringBuilder();
if (number > long.MaxValue - min)
{
number = long.MaxValue - min;
}
List<long> vector = new List<long>(10);
vector.Add(min - 1 + number);
long range = max - min + 1;
bool nextLetter = false;
for (int i = 0; i < vector.Count; i++)
{
long nextLetterCounter = 0;
while (vector[i] > max)
{
nextLetter = true;
long multiplicator = Math.Abs(vector[i] / range);
if ((vector[i] - (multiplicator * range)) < min)
{
multiplicator -= 1;
}
vector[i] = vector[i] - (multiplicator * range);
nextLetterCounter += multiplicator;
}
if (nextLetter)
{
vector.Add((min + nextLetterCounter - 1));
nextLetter = false;
}
text.Append((char)(vector[i]));
}
return text.ToString();
}
}
}
答案 0 :(得分:1)
我通常避免帮助解决这些问题,因为上下文本质上是恶意的,我不知道你或你对代码的意图。但是,我会告诉您,您的测试已经存在缺陷,因为您正在连续测试它们,应用程序获得类似CPU周期等的可能性很小。我建议使用实际的分析工具来实际测试这些数据,例如Visual Studio Performance Tools或其他一些分析套件,它们通常还包括比较结果的工具。
投票结束,可能重复: Java vs C#: Are there any studies that compare their execution speed?
答案 1 :(得分:1)
尝试添加-o2
编译器标志。这应该可以提高c#的性能。
答案 2 :(得分:1)
简短的回答是,你的任务越小,相对开销越大。开销很大程度上是固定的,可能比您尝试执行的任务高10到1000倍。在每个任务中尝试执行10 - 10,000x的工作,使开销相对较小。理想情况下,只需将所有工作划分为N个任务(其中N是您拥有的核心数量,例如Runtime.getRuntime().availableProcessors()
)这样,您的所有核心都将忙碌,您将不必担心队列大小(它将是0;)
更长的答案......
我会确保你在所有情况下使用-server
因为这可以改善基准(或至少给你更一致的结果)
当您创建一个多线程进程时,您会增加开销(锁定/同步/缓存一致性),并且作为回报,您的任务可以同时运行。编写一个比并发性更高的开销的程序非常容易。
这篇文章是关于从一个简单的例子编写多线程程序的一些陷阱中写的一篇文章,以及多线程程序如何更慢,速度慢得多(数万亿倍)http://vanillajava.blogspot.com/2011/11/why-concurency-examples-are-confusing.html < / p>