Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
#вакансия#vacancy#DA#analyst#senior#remote#fulltime#optimization
Вакансия: Middle+/Senior Data Analyst (с опытом в оптимизационных задачах)
Формат: Удалённый
Занятость: Полная
Оплата: 3500 - 4500$ net.
Ptolemay - аутсорсинговая IT-компания полного цикла по разработке мобильных и веб-приложений для бизнеса и стартапов. Ищем ML Engineer для аутстафф-проекта в сфере металлургии.
Обязанности:
- Разрабатывать и внедрять алгоритмы оптимизации для объемно-календарного планирования.
- Осуществлять постановку и решение задач LP, NLP, определять целевые функции и ограничения.
- Автоматизировать планирование в промышленности или смежных областях.
- Работать с пакетами оптимизации (SciPy, Pyomo, CVXPY, OptaPlanner) и солверами (COBYLA, Ipopt и др.).
Требования:
- Опыт работы по функциональному направлению от 4-х лет.
- Знание языков программирования Python либо Java.
- Знание основных типов оптимизационных задач (LP, NLP и т.д.).
- Опыт работы с пакетами оптимизации (SciPy, Pyomo, CVXPY, OptaPlanner или аналогичные).
- Опыт работы с различными солверами (COBYLA, Ipopt и другие), понимание принципов их работы (сильные и слабые стороны).
- Опыт линеаризации задач, постановка целевой функции и ограничений.
- Опыт постановки задачи, разбиение на подзадачи.
Условия работы:
- Удалённый формат работы.
- Полная занятость.
- Оформление по ИП, СМЗ.
- Оплата 3500 - 4500$ net.
Буду рад ответить на вопросы и ознакомиться с резюме: @Dmitriy_Ptolemay
BuyerCaddy Secures $1.5M Funding
BuyerCaddy has successfully raised $1.50M in funding as of December 19, 2024. The platform focuses on cost savings, optimization, and tech stack benchmarking, helping users identify redundant products, track utilization, and enhance integrations.
#Funding#BuyerCaddy#TechStack#Optimization#CostSavings
Ekore Secures $1.35M Funding
Ekore raised $1.35M in funding, set to enhance building management through optimized consumption and maintenance via the Digital Twin concept. For more information, visit Ekore.
#Ekore#Funding#DigitalTwin#BuildingManagement#Optimization
#python#agents#document_search#evaluation#guardrails#llms#optimization#prompts#rag#vector_stores
Ragbits is a tool that helps build and deploy GenAI applications quickly. It offers features like swapping between many language models, ensuring safe interactions with these models, and connecting to various data storage systems. Ragbits also includes tools for managing data and testing prompts, making it easier to develop reliable AI applications. This helps users create more accurate and efficient AI systems by integrating the latest data and reducing errors. Overall, Ragbits makes it faster and more efficient to develop and deploy AI applications.
https://github.com/deepsense-ai/ragbits
#java#aerospace#flight_simulator#java#modeling#optimization#rocket#rocketry#simulation#trajectory
OpenRocket is a free tool to design, visualize in 3D, and simulate model rockets with six-degree-of-freedom flight analysis, real-time data on altitude/velocity, automatic optimization, and exports for 3D printing or other programs. It works on any platform via Java. You benefit by testing rockets virtually first, saving time/money on failed builds, predicting performance accurately, and flying safer, higher with optimized designs.
https://github.com/openrocket/openrocket
Future of AI Search Optimization
A new market emerges as users shift from traditional Google searches to AI tools like ChatGPT and Claude. The $70 billion search optimization industry sets the stage for a vast new optimization market focused on AI responses. Early entrants can capitalize on this shift with relatively simple platforms. Discover more: Read Here
#AI#SearchOptimization#ChatGPT#Claude#Perplexity#MarketTrends#Innovation#TechIndustry#BusinessOpportunities#DigitalMarketing#InformationRetrieval#Technology#Entrepreneurship#FutureOfWork#Investment#Strategy#Growth#Optimization#Startups
#python#ant_colony_algorithm#artificial_intelligence#fish_swarms#genetic_algorithm#heuristic_algorithms#immune#immune_algorithm#optimization#particle_swarm_optimization#pso#simulated_annealing#travelling_salesman_problem#tsp
You can use scikit-opt, a Python library offering many heuristic optimization algorithms like Genetic Algorithm, Particle Swarm Optimization, Simulated Annealing, Ant Colony, Immune Algorithm, and Artificial Fish Swarm Algorithm. It supports user-defined functions to customize operators, allows continuing runs from previous iterations, and accelerates computations via vectorization, multithreading, multiprocessing, and caching. GPU support is in development. It helps solve complex optimization problems such as function minimization and the Traveling Salesman Problem efficiently, with easy installation and rich examples. This saves you time and effort in implementing and tuning optimization algorithms yourself.
https://github.com/guofei9987/scikit-opt