Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
from timeit import timeit
def t1():
# складываем 10 строк через + из переменной
t = 'text'
for _ in range(1000):
s = t + t + t + t + t + t + t + t + t
def t2():
# склеиваем список строк через метод join
arr = ['text'] * 10
for _ in range(1000):
s = ''.join(arr)
def t3():
# складываем через + но не из переменной а непосредственно инлайн объекты
for _ in range(1000):
s = 'text' + 'text' + 'text' + ... # всего 10 раз
Теперь каждую строку склейки запустим по 10М раз
>>> timeit(t1, number=10000)
0.21951690399964718
>>> timeit(t2, number=10000)
1.4978306379998685
>>> timeit(t3, number=10000)
0.2213820789993406
Хм, а нам говорили что через "+" это плохо и медленно ))) 😁
Тут стоит учитывать, что речь идёт о склейке множества длинных строк.
Давайте изменим условия:
def t4():
t = 'text'*100
for _ in range(1000):
s = t + t + t + t + t + t + t + t + t
def t5():
arr = ['text'*100] * 10
for _ in range(1000):
s = ''.join(arr)
def t6():
for _ in range(1000):
s = 'text'*100 + 'text'*100 + ... # всего 10 раз
>>> timeit(t4, number=10000)
12.795130728000004
>>> timeit(t5, number=10000)
2.642637542999182
>>> timeit(t6, number=10000)
0.2184546610005782
Вот, уже другой разговор, сразу видна разница, в среднем в 6 раз. Но погодите, почему последний тест t6() по скорости такой же как и t3()? Ведь строки теперь в 100 раз длиннее!
Это вопросы оптимизации кода, какие простые изменения ускоряют или замедляют выполнение программы. Мы столкнулись с примером обхода обращения к переменной. Например, именно так работает директива #define в С++, во время компиляции подставляя значение переменной вместо ссылки на неё.
В Python это тоже работает, но часто ли вы сможете встретить такой способ работы со строками? К сожалению, способ почти только теоретический.
В целом, тесты показали то, что мы хотели. Делаем выводы самостоятельно.
Полный листинг 🌍
#tricks
📰 FFmpeg Introduces Vulkan-Accelerated 360 Degree Video Conversion
Beyond the capabilities of just the Vulkan Video API, the FFmpeg multimedia library has made interesting Vulkan-accelerated adaptations using compute shaders. With Vulkan compute they've implemented Apple ProRes video acceleration, FFV1 decode, and other features. The newest Vulkan feature now in place for FFmpeg is 360 degree video conversion...
🔗 Source: https://www.phoronix.com/news/FFmpeg-360-Degree-Vulkan
#ffmpeg
📰 FFmpeg 8.1 Released With Experimental xHE-AAC MPS212, More Vulkan Acceleration
FFmpeg 8.1 is out today as the newest stable release of this widely-used, open-source multimedia library...
🔗 Source: https://www.phoronix.com/news/FFmpeg-8.1-Released
#opensource#ffmpeg
📰 Gentoo-Based Redcore Linux Hardened 2601 Released with Kernel 6.19
Redcore Linux Hardened 2601 Vulpecula has been released, featuring Linux kernel 6.19, FFmpeg 8, and updates to the Sisyphus package manager.
🔗 Source: https://linuxiac.com/gentoo-based-redcore-linux-hardened-2601-released-with-kernel-6-19/
#ffmpeg#kernel#linux
Кстати! Я всем советую попробовать HandBrake — программу для ужатия видео.
Это графический интерфейс для мощной библиотеки ffmpeg, которая заточена на перегонку видео в разные форматы.
Я в основном использую для уменьшения размера файлов, чтобы телеграм проигрывал их без звука автоматически
Тут подробнее писал как это работает
Анимацию постом выше я просто закинул и без изменения настроек перегнал из mpg в mp4. Размер изменился с 4.5мб до 300кб
А для тизера «Коротких вопросов» нажав две кнопки, смог уменьшить файл со 167 мб до (!) 3 мб. За счет уменьшения размера сторон с 4к до 720p.
На мобиле разницы скорее всего не будет видно, а вовлечение в просмотр повысится — сплошная польза!
Работает на всех платформах, в том числе на маке и линуксе!
🎤Ссылки на утро — второй канал
⏲Ускорить YouTube за звезду (VPN за 2₽)
#ToolReview@cogload#ffmpeg@cogload#telegram@cogload
🔖 The creator of ffmpeg Fabrice Bellard(1) is truly a genius and has created so many amazing software that have been an amazing benefit to the world. | Hacker News #pinboard#pantheon#ffmpeg#person
Yeah definitely. If programming genius had a unit it should be called the bellard.
One 10x programmer = a 1/10th Bellard?
100x 工程师,可以放在万神殿了
https://news.ycombinator.com/item?id=25487711
This is Probably the Best Video Downloader App (And it is Free and Open Source) | itsFOSS
VidBee allows you to download videos from YouTube, Facebook, X, Instagram, etc. In fact, it supports over 1,800 websites.
It is built on top of popular command line tools like yt-dlp and #ffmpeg. For the interface, it uses the Electron framework. I understand that some people dislike Electron framework as it runs a web browser underneath, but the 'advantage' of this framework is that you get the same interface in all the operating systems. At least, it's an advantage for the developers as they don't have to build the interface separately for #Linux, #Windows and #macOS.
The source code for VidBee is available on its GitHub repository.
#VidBee - Free Open Source Video Downloader
https://vidbee.org/