Во -первых, мы создаем случайный двоичный файл с 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 мс
, что на самом деле не отличается от секундомерного часа. < /P>
Подробнее здесь: https://stackoverflow.com/questions/796 ... ed-to-java
Почему этот код в 5 раз медленнее в C# по сравнению с Java? ⇐ C#
Место общения программистов C#
-
Anonymous
1750679208
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[i] = byteArray[i];
}
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 мс
, что на самом деле не отличается от секундомерного часа. < /P>
Подробнее здесь: [url]https://stackoverflow.com/questions/79675833/why-is-this-code-5-times-slower-in-c-sharp-compared-to-java[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия