Почему этот код в 5 раз медленнее в C# по сравнению с Java?C#

Место общения программистов C#
Ответить
Anonymous
 Почему этот код в 5 раз медленнее в C# по сравнению с Java?

Сообщение Anonymous »

Во -первых, мы создаем случайный двоичный файл с 100 000,000 байтов. Я использовал Python для этого: < /p>
import random
import os

def Main():
length = 100000000
randomArray = random.randbytes(length)
desktopPath = os.path.normpath(os.path.expanduser("~/Desktop"))
fullPath=os.path.join(desktopPath,"RandomFile.dat")
if os.path.isfile(fullPath):
print("File already exists.")
return
with open(fullPath, "wb") as file:
file.write(randomArray)
print("The file has been created.")

Main()
< /code>
После этого мы обнаруживаем, сколько из этих байтов было больше, чем 100, используя C# и Java. < /p>
c#: < /p>
using System.Diagnostics;

namespace TestYouTube
{
public class Program
{
//finished
public static void Main(string[] args)
{
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fullPath = Path.Combine(desktopPath, "RandomFile.dat");
if (!File.Exists(fullPath))
{
Console.WriteLine("The file does not exist.");
return;
}
byte[] byteArray = File.ReadAllBytes(fullPath);
int[] intArray = ByteArrayToIntArray(byteArray);
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int count = TestSpeed(intArray);
stopwatch.Stop();
Console.WriteLine($"Count = {count}");
Console.WriteLine($"Elapsed: {stopwatch.Elapsed.TotalSeconds} seconds");
Console.ReadLine();
}

//finished
private static int[] ByteArrayToIntArray(byte[] byteArray)
{
if (byteArray == null) return null;
if (byteArray.Length == 0) return Array.Empty();
int[] intArray = new int[byteArray.Length];
for (int i = 0; i < intArray.Length; i++)
{
intArray = byteArray;
}
return intArray;
}

//finished
private static int TestSpeed(int[] array)
{
if (array == null) throw new ArgumentNullException();
if (array.Length == 0) throw new ArgumentException();
int count = 0;
foreach (int element in array)
{
if (element > 100)
{
count++;
}
}
return count;
}
}
}
< /code>
java: < /p>
import javax.swing.filechooser.*;
import java.io.*;
import java.nio.file.*;

public class Main
{
public static void main(String[] args) throws IOException
{
FileSystemView view = FileSystemView.getFileSystemView();
File file = view.getHomeDirectory();
String desktopPath = file.getPath();
Path fullPath = Paths.get(desktopPath,"RandomFile.dat");
File randomFile=new File(fullPath.toString());
if (!randomFile.exists() || randomFile.isDirectory())
{
System.out.println("The file does not exist.");
return;
}
byte[] array = Files.readAllBytes(randomFile.toPath());
int[] intArray=ByteArrayToUnsignedByteArray(array);
long start = System.currentTimeMillis();
int count=TestSpeed(intArray);
long end = System.currentTimeMillis();
long elapsed=end-start;
double elapsedSeconds=((double)elapsed)/1000;
System.out.printf("Count = %d\n",count);
System.out.printf("Elapsed: %f seconds\n",elapsedSeconds);
}

private static int ByteToUnsignedByte(byte b)
{
return b & 0b11111111;
}

private static int[] ByteArrayToUnsignedByteArray(byte[] byteArray)
{
if (byteArray==null) return null;
if (byteArray.length==0) return new int[0];
int[] newArray=new int[byteArray.length];
for (int i=0;i100)
{
count++;
}
}
return count;
}
}
< /code>
Обратите внимание, что мы измеряем только время функции TestSpeed ​​на обоих языках. < /p>
Результаты:
c#:

count = 60542647

leleps: 0,4286155 секунд < /p>
java: 0,4286155 seconds < /p>
java: 0,4286155 seconds < /p>
java: 0,4286155 seconds < /p>
java: 0,4286155 секунд. 60542647

alpsed: 0,077000 секунд < /p>
Я запускал код несколько раз, и результат примерно одинаково. C# примерно в 5 раз медленнее, чем Java. Обратите внимание, что я запустил код из «Выпуск», а также я использовал «Start без деббугинга». < /P>
Кто -нибудь знает, почему это происходит? Что я делаю не так? Результаты:
TestSpeed ​​Среднее значение: 411,2 мс
, которое на самом деле не отличается от секундомата. /> Имя процессора: AMD ATHLON GOLD 3150U с Radeon Graphics < /p>

Подробнее здесь: https://stackoverflow.com/questions/796 ... ed-to-java
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»