Edit: I will try to specify my question better. I'm not asking about how to measure the performance or anything or how to write the algorithm. I tried to mirror the source of the java application into C#. The java codes runs about 1.3 - 2.0 times faster than the C# code. So why is it like that? Did i make a mistake in porting the code? Are the threads of the ExecutorService in java the same as the c# tasks? Why is even java singlethreaded faster than c# multithreaded ( java multithreaded is the fastest )?
For testing purposes (getting back into the languages) I coded a pseudo brute force application in Java and later ported it to C#. I tried to change the least possible so that both sources stay the same semantically. I know that these pieces of code aren't perfect and please don't try to correct the algorithm behind it as this is not related to the question.
The Question: So when I run both applications consecutively and then compare the output, Java is faster in every try and Java singlethreaded is almost as fast or faster than C# multithreaded. I want to know why it is like that and maybe what I did wrong (if anything) in the C# version of the code. Any hints on fatal coding mistakes? Also, on the Windows XP configuration C# multithreaded is slower than C# singlethreaded (how is this even possible?).
Tried it on 2 configurations:
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
I'm posting the code so you can test yourself.
Java Code:
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();
}
}
And C# Code:
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();
}
}
}