Linux on usb speed

Проверка скоростного режима USB-портов в Linux

Дмитрий Корнев

Когда мой компьютер работал под управлением Windows, то для интерфейса USB 3.0 требовалось установить драйвер от производителя материнской платы. Операционная система не могла найти его самостоятельно. С переходом на Linux такой проблемы не стало. Все имеющиеся порты USB при установке системы начинают работать сразу. Но полноценно ли? В этой статье несколько простых способов, позволяющих проверить версию интерфейса и режим работы подключенных к нему устройств.

Просмотр информации по всем USB-контроллерам компьютера:

Материнская плата ASRock H67M-GE не новая. На ней преобладают порты USB 2.0, поддержка которых сразу заложена в чипсете. Дополнительно присутствует контроллер USB 3.0 от Etron Technology. В выдаче это всё видно, значит все контроллеры настроены правильно:

Для ноутбука Acer TMX349-M-535L выдача оказалось проще. Контроллер USB лишь один и по версии вопросов тоже не остаётся:

Если так окажется, что в выдаче не будет чётко указана версия USB-контроллера, то можно проискать в интернете информацию по выданному наименованию контроллера.

Следующая команда позволяет получить значительно более детальную информацию по всему, что связанно с USB. Видно контроллеры, порты, устройства, техническую информацию по устройствам, скоростные режимы работы каждого устройства, возникшие ограничения в работе устройств, историю подключения-отключения устройств.

В выдаче high-speed USB и SuperSpeed USB — это устройства USB 2.0 и USB 3.0, соответственно.

Пример для ASRock H67M-GE:

Бывает, что USB-порты работают. И даже их версия такая, какая должна быть. Но скорость обмена данными оставляет желать лучшего. Поставить точку в вопросе скорости поможет тестирование каким-нибудь USB-носителем. Берём флешку или диск. Обязательно USB 3.0, если хотим проверить соответствующий порт. Подключаем к нужному порту и запускаем скоростной тест.

У меня есть внешний жёсткий диск и флешки, для которых я примерно знаю максимальные скорости. Сравнивая полученные значения становится ясно, на какой скорости позволяет им работает USB-порт.

Если вы не знаете скоростные характеристики своих USB-носителей, то можно просто сравнить, дополнительно подключив их к заведомо низкоскоростным портам. Или через USB-хаб версии 2.0, который тоже замедлит работу.

Мне нравится для подобных тестов использовать «Дисковую утилиту Gnome»:

Примеры тестов одного и того же USB-диска через USB 2.0 и USB 3.0 можно посмотреть в недавнем обзоре. Они выполнены как раз через эту программу. И разница скоростей очевидна.

Источник

Linux on usb speed

23 апр 2017, 08:34

Как быстр ваш USB? Как быстр ваш SSD-накопитель? Это очень распространенный вопрос. Я собрал и скомпилировал несколько тестов, которые помогут вам выполнить тест скорости USB и SSD в Linux. Когда я говорю speedtest, я тестирую скорость чтения / записи USB и SSD дисков. Это также сообщит вам, работают ли ваши накопители на максимальной скорости.

Скорость привода измеряется с точки зрения того, сколько данных он может читать или записывать за единицу времени. Команда dd — это простой инструмент командной строки, который может использоваться для чтения и записи произвольных блоков данных на диск и измерения скорости передачи данных. В этом посте мы будем использовать команду dd для проверки скорости чтения SSD и USB-накопителей .

Скорость передачи данных зависит не только от диска, но и от интерфейса, к которому он подключен. Например, порт USB 2.0 имеет максимальную скорость работы 35 Мбайт / с, поэтому, даже если вы подключите высокоскоростной накопитель USB 3 к порту USB 2, скорость будет ограничена нижним пределом.

То же самое касается SSD. SSD подключаются через порты SATA, которые имеют разные версии. Sata 2.0 имеет максимальный теоретический предел скорости 3Gbits / s, который составляет примерно 375 Мбайт / с. В то время как Sata 3.0 поддерживает вдвое большую скорость.

Установите привод и перейдите в него с терминала. Затем с помощью команды dd сначала запишите файл, используя блоки фиксированного размера. Затем прочитайте тот же файл, используя тот же размер блока.

Общий синтаксис команды dd выглядит следующим образом:

dd if=path/to/input_file of=/path/to/output_file bs=block_size count=number_of_blocks

Читайте также:  Не удалось найти исходные файлы dism 0x800f081f windows

При записи на диск мы просто читаем /dev /zero, который является источником бесконечных бесполезных байтов. И когда читаем с диска, мы читаем файл, написанный ранее, и отправляем его в /dev /null, который нигде не существует. Во всем процессе dd отслеживает скорость, с которой происходит передача, и сообщает об этом.

Файл tempfile , который только что был создан предыдущей командой, был кэширован в буфере, и его скорость чтения намного выше реальной скорости чтения непосредственно с жесткого диска. Чтобы получить реальную скорость, нам нужно очистить кэш.

Выполните следующую команду, чтобы узнать скорость чтения из буфера:

$ dd if=tempfile of=/dev/null bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 0.159273 s, 6.7 GB/s

Очистите кэш Linux и измерите реальную скорость чтения напрямую с жесткого диска:

$ sudo /sbin/sysctl -w vm.drop_caches=3
vm.drop_caches = 3
$ dd if=tempfile of=/dev/null bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 2.27431 s, 472 MB/s

Выполните следующую команду для проверки скорости записи на жестком диске:

$ sync; dd if=/dev/zero of=tempfile bs=1M count=1024; sync
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 3.28696 s, 327 MB/s

Теперь давайте начнем с инструкций для проверки скорости чтения SSD. Наш SSD подключается к порту SATA 2.0 для этого теста.

Скорость записи.

$ dd if=/dev/zero of=./largefile bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 4.82364 s, 223 MB/s

Размер блока на самом деле довольно большой. Вы можете попробовать с меньшими размерами, такими как 64k или даже 4k.

Скорость чтения.

Теперь прочитайте тот же файл. Однако сначала очистите кэш памяти, чтобы убедиться, что файл действительно считывается с диска.
Выполните следующую команду, чтобы очистить кэш памяти:

$ sudo sh -c «sync && echo 3 > /proc/sys/vm/drop_caches»

Теперь прочитайте файл:

$ dd if=./largefile of=/dev/null bs=4k
165118+0 records in
165118+0 records out
676323328 bytes (676 MB) copied, 3.0114 s, 225 MB/s

В этом тесте мы будем измерять скорость чтения и записи обычных USB / PEN-дисков. Диски подключены к стандартным портам USB 2. Первый — это USB-накопитель Sony 4GB, а второй — Strontium 16-Гбайт.

Сначала подключите диск к порту и установите его, чтобы он читался. Затем перейдите в каталог монтирования из командной строки.

Скорость чтения / записи внешнего жесткого диска

Чтобы проверить производительность некоторых внешних жестких дисков, USB-накопителей или любого другого съемного устройства или удаленной файловой системы, просто обратитесь к точке монтирования и повторите указанные выше команды.
Или вы можете заменить временный файл на путь к точке монтирования, например

$ sync; dd if=/dev/zero of=/media/user/MyUSB/tempfile bs=1M count=1024; sync
Все вышеприведенные команды используют временный файл tempfile. Не забудьте удалить его, когда вы завершите тесты.

Sony 4GB — Запись

В этом тесте команда dd используется для записи 10 000 блоков по 8 Кбайт каждый в один файл на диске.

# dd if=/dev/zero of=./largefile bs=8k count=10000
10000+0 records in
10000+0 records out
81920000 bytes (82 MB) copied, 11.0626 s, 7.4 MB/s

Таким образом, скорость записи составляет около 7,5 Мбайт / с. Это низкая цифра.

Sony 4GB — Чтение.

Тот же файл считывается обратно для проверки скорости чтения. Выполните следующую команду, чтобы очистить кэш памяти:

$ sudo sh -c «sync && echo 3 > /proc/sys/vm/drop_caches»

Теперь прочитайте файл, используя команду dd.

# dd if=./largefile of=/dev/null bs=8k
8000+0 records in
8000+0 records out
65536000 bytes (66 MB) copied, 2.65218 s, 24.7 MB/s

Скорость чтения составляет около 25 Мбайт / с, что является более или менее стандартным для дешевых USB-накопителей.

Максимальная скорость передачи USB 2.0 составляет 480 Мбит / с или 60 Мбайт / с. Однако из-за различных ограничений максимальная пропускная способность ограничена примерно 280 Мбит / с или 35 Мбайт / с. Помимо этого, фактическая скорость зависит от качества Pen приводов и других факторов.

Вышеупомянутый USB-накопитель был подключен к порту USB 2.0 и достиг скорости чтения 24,7 Мб / с, что не очень плохо. Но скорость записи значительно отстает

Теперь давайте сделаем тот же тест с приводом Stronium 16GB. — Stronium еще один очень дешевый бренд, хотя USB-накопители надежны.

Скорость записи Stronium 16 ГБ

# dd if=/dev/zero of=./largefile bs=64k count=1000
1000+0 records in
1000+0 records out
65536000 bytes (66 MB) copied, 8.3834 s, 7.8 MB/s

Скорость чтения Stronium 16gb

# sudo sh -c «sync && echo 3 > /proc/sys/vm/drop_caches»
# dd if=./largefile of=/dev/null bs=8k
8000+0 records in
8000+0 records out
65536000 bytes (66 MB) copied, 2.90366 s, 22.6 MB/s

Скорость чтения ниже, чем у накопителя Sony.

Hdparm — это утилита Linux, которая позволяет быстро узнать скорость чтения жесткого диска. Установите hdparm в зависимости от дистрибутива Linux.
В Linux Mint, Ubuntu, Debian:

$ sudo apt-get install hdparm

Запустите hdparm следующим образом, чтобы измерить скорость чтения жесткого диска /dev/sda:

Читайте также:  Stablauncher для windows 10

$ sudo hdparm -Tt /dev/sda
/dev/sda:
Timing cached reads: 16924 MB in 2.00 seconds = 8469.95 MB/sec
Timing buffered disk reads: 1386 MB in 3.00 seconds = 461.50 MB/sec

Источник

2E0PGS / linux-usb-file-copy-fix.md

If your running a x64 bit Ubuntu or other Linux and find USB transfers hang at the end apply this fix:

I suggest you edit your /etc/rc.local file to make this change persistant across reboots.

sudo nano /etc/rc.local

Go to the bottom of the file and leave a space then paste in those two lines.

Save the file with ctrl + x then press y.

To revert the changes enter this in console and remove the lines in /etc/rc.local

This comment has been minimized.

Copy link Quote reply

jorgeribeiro commented Oct 24, 2018

It worked just fine, thank you so much!

After searching a lot in different sources, this was the only answer to actually work.
I use Linux Mint 18.

This comment has been minimized.

Copy link Quote reply

Oldbuntu commented Jan 24, 2019

Thank’s this really work for Ubuntu 18.04.Thank one’s again

This comment has been minimized.

Copy link Quote reply

Rockburner commented Feb 20, 2019 •

I tried entering these lines into the file, but now a 1Gb file that previously took less than a minute to copy, after which ‘files’ would hang for over an hour, is taking up to an hour to copy at something like 255kB/sec.
For reference the machine is an I5 with 16GbRAM running ubuntu 18.04. The USB stick is a new 256Gb SanDisk.
Are there some better byte values I can try to get a better balance between the latency and the hanging?

I can’t use the lines directly in the terminal either — I just get ‘Permission Denied’, even using sudo.

Источник

Test read/write speed of usb and ssd drives with dd command on Linux

Drive speed

The speed of a drive is measured in terms of how much data it can read or write in unit time. The dd command is a simple command line tool that can be used to read and write arbitrary blocks of data to a drive and measure the speed at which the data transfer took place.

In this post we shall use the dd command to test and read and write speed of usb and ssd drives using the dd command.

The data transfer speed does not depend solely on the drive, but also on the interface it is connected to. For example a usb 2.0 port has a maximum operational speed limit of 35 Mbytes/s, so even if you were to plug a high speed usb 3 pen drive into a usb 2 port, the speed would be capped to the lower limit.

The same applies to SSD. SSD connect via SATA ports which have different versions. Sata 2.0 has a maximum theoretical speed limit of 3Gbits/s which is roughly 375 Mbytes/s. Whereas Sata 3.0 supports twice that speed.

Test Method — The dd command

Mount the drive and navigate into it from the terminal. Then use the dd command to first write a file using fixed sized blocks. Then read the same file out using the same block site.

The general syntax of the dd command looks like this

When writing to the drive, we simply read from /dev/zero which is a source of infinite useless bytes. And when read from the drive, we read the file written earlier and send it to /dev/null which is nowhere. In the whole process, dd keeps track of the speed with which the transfer takes place and reports it.

SSD Drive

The SSD that we are using is a «Samsung Evo 120GB» ssd. It is a beginner level ssd that comes within a decent budget and is also my first SSD. It is also one of the best performing ssds, in the market.

In this test the ssd is connected to a sata 2.0 port.

Lets first write to the ssd

Block size is actually quite large. You can try with smaller sizes like 64k or even 4k.

Now read back the same file. However, first clear the memory cache to ensure that the file is actually read from drive.

Run the following command to clear the memory cache

Now read the file

The Arch Linux wiki has a page full of information about the read/write speed of various SSDs from different vendors like Intel, Samsung, Sandisk etc. Check it out at the following url.

Читайте также:  Что защищает windows defender

USB Pen drives

In this test we shall measure the read and write speed of ordinary usb/pen drives. The drives are plugged to standard usb 2 ports. The first one is a sony 4gb usb drive and the second is a strontium 16gb drive.

First plug the drive into the port and mount it, so that it is readable. Then navigate into the mount directory from the command line.

Sony 4GB USB 2.0 Drive

Sony 4GB — Write

In this test, the dd command is used to write 10,000 chunks of 8 Kbyte each to a single file on the drive.

So the write speed is around 7.5 MBytes/s. This is a low figure.

The same file is read back to test the read speed. Run the following command to clear the memory cache

Now read the file using the dd command

The read speed comes out around 25 Mbytes/s which is a more or less the standard for cheap usb drives.

And the above usb drive was plugged inside a USB 2.0 port and it achieved a read speed of 24.7 Mbytes/s which is not very bad. But the write speed lags much behind

Strontium USB 2.0 16GB Pen drive

Now lets do the same test with a Strontium 16gb drive. Strontium is another very cheapy brand, although usb drives are reliable.

Strontium 16gb read speed

The read speed is lower than the Sony drive.

SanDisk Cruzer Blade 32GB USB Flash Drive

This is a popular cheap USB 2.0 drive available on amazon.in
Lets test its read and write speed.

Read Speed — CPU Case USB Port

Reading a simple iso file present on the drive using the dd command.

The read speed is about 27.3 MB/s

Write Speed — CPU Case USB Port

Now lets test the write speed

The write speed is quite low at 4.4 MB/s.

Sandisk Ultra CZ48 USB 3.0 16 GB Pen Drive

Read speed — Motherboard USB Port

This one has a decent read speed.

Write speed — Motherboard USB Port

Lets copy the same ubuntu iso file from disk to the usb drive

The write speed this time is better than the earlier Sandisk USB 2.0 drive.

Motherboard USB Port vs CPU case USB Port — Big Difference!

The speed also depends on whether you connect the USB drive to the front ports on your cpu case or directly on the motherboard usb ports. As you might be able to guess already, the speed on motherboard usb ports is significantly higher.

Front of CPU Case — Sony USB 3.1 Gen 16GB — Read Speed

Motherboard USB Port — Sony USB 3.1 Gen 16GB — Read Speed

So the motherboard usb port speed is almost 3X higher than the cpu case usb ports. So if you are planning to do heavy data transfer, then it would be a better idea to make the extra effort of connecting the usb drive to the back of your CPU.

Motherboard USB Port — Sony USB 3.1 Gen 16GB — Write Speed

The write speed of this Sony USB 3.1 drive is lower than the Sandisk Ultra USB 3.0 Drive. Both of them were tested on motherboard usb ports.

Resources

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

5 thoughts on “ Test read/write speed of usb and ssd drives with dd command on Linux ”

[email protected]:/home/home$ sudo dd if=/dev/zero of=./largefile bs=1M count=1024
[sudo] password for anon:
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 0.989448 s, 1.1 GB/s

how is this possible?

dd if=/dev/zero of=./largefile bs=1M count=1024 is just writing to ram, tho.

Nice post!
On my machine (distro: Mageia), pendrives are cached by kernel.
So, a simple dd do not measure the real write speed (dd reports 63MB/s).
So I disabled the cache with the sync option of mount.
dd now reports 170 KB/s (big difference)

Looking at your write speed results, I suspect that your pendrive is also cached by the kernel.

if dd command is used to monitor performance of a drive especially for a usb disk, conv=fsync should be set in order to flush the memory each time during the write operation.

sudo hdparm -t /dev/sdxx is far safer than dd which I would never recommend anyone run to benchmark a drive ever

Источник

Оцените статью