蛮力性能:Java vs C#

蛮力性能:Java vs C#,c#,java,performance,benchmarking,C#,Java,Performance,Benchmarking,编辑:我将尝试更好地指定我的问题。我不是在问如何衡量性能或任何事情,也不是在问如何编写算法。我试图将java应用程序的源代码镜像到C#。java代码的运行速度大约是C代码的1.3-2.0倍。那为什么是这样呢?我在移植代码时出错了吗?java中ExecutorService的线程是否与c#任务相同?为什么java单线程比c多线程更快(java多线程是最快的) 出于测试目的(回到语言中),我用Java编写了一个伪暴力应用程序,然后将其移植到C#。我试图尽可能少地进行更改,以便两个源在语义上保持相同。

编辑:我将尝试更好地指定我的问题。我不是在问如何衡量性能或任何事情,也不是在问如何编写算法。我试图将java应用程序的源代码镜像到C#。java代码的运行速度大约是C代码的1.3-2.0倍。那为什么是这样呢?我在移植代码时出错了吗?java中ExecutorService的线程是否与c#任务相同?为什么java单线程比c多线程更快(java多线程是最快的)

出于测试目的(回到语言中),我用Java编写了一个伪暴力应用程序,然后将其移植到C#。我试图尽可能少地进行更改,以便两个源在语义上保持相同。我知道这些代码并不完美,请不要试图纠正其背后的算法,因为这与问题无关

问题是: 因此,当我连续运行两个应用程序,然后比较输出时,Java在每次尝试中都会更快,Java单线程几乎与C#多线程一样快或更快。我想知道为什么会这样,也许我在C版本的代码中做错了什么(如果有的话)。有关于致命编码错误的提示吗? 另外,在WindowsXP配置中,多线程比单线程慢(这怎么可能呢?)

在2种配置上进行了尝试:

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();
}
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();
    }
}
}
使用系统;
使用System.Collections.Generic;
使用系统文本;
使用系统诊断;
使用System.Threading.Tasks;
使用系统线程;
名称空间密码破解程序
{
公共类密码破解器
{
字符串密码跟踪;
找到公共bool密码;
int-min;
int max;
StringBuilder破解密码;
公共空白准备(字符串文本)
{
PasswordToTrack=文本;
passwordFound=false;
最小值=32;
max=126;
crackedPassword=新的StringBuilder();
crackedPassword.Append((char)(min-1));
}
公开结果()
{
Console.Out.WriteLine(“破解密码为:+crackedPassword.ToString());
}
public void incrementString(StringBuilder文本,最小整数,最大整数)
{
文本[0]=(字符)((文本[0])+1);
for(int i=0;i(字符)(最大值))
{
文本[i]=(字符)(最小值);
if(text.Length==i+1)
{
text.Append((char)(min));
}
其他的
{
文本[i+1]=(字符)((文本[i+1])+1);
}
}
}
}
公共void runMulti(字符串文本)
{
编写(文本);
秒表时间=新秒表();
time.Start();
doItMulti();
Console.Out.WriteLine(时间.已用时间.总秒数);
结果();
}
公共void runSingle(字符串文本)
{
编写(文本);
秒表时间=新秒表();
time.Start();
doitingle();
Console.Out.WriteLine(时间.已用时间.总秒数);
结果();
}
公共无效doitingle()
{
while(passwordFound==false)
{
递增字符串(crackedPassword,最小值,最大值);
passwordFound=crackedPassword.ToString().Equals(passwordToCrack);
}
}
public void doItMulti()
{
int cores=Environment.ProcessorCount;
长步长=2000;
列表任务=新列表(核心);
对于(长i=0;icores)
{
for(int a=0;along.MaxValue-min)
{
数字=long.MaxValue-min;
}
列表向量=新列表(10);
矢量加(最小值-1+数字);
远程=最大-最小+1;
bool-nextLetter=false;
对于(int i=0;imax)
{
nextLetter=true;
长乘法器=Math.Abs(向量[i]/范围);
if((向量[i]-(乘法器*范围))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();
    }
}
}