TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #32 · 7 фев.

Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять: 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

Резултати

Пронајдени 1 слични објави

Пребарај: #vivektavinita

当前筛选 #vivektavinita清除筛选
Pensive|

@PensivePost · Post #5848 · 08.07.2022 г., 21:06

I rushed down stairs. The wild energy around her was affecting me. Not only affecting me but turning me into the perfect dumbass. So I thought its good idea if I catch up with my buddy before a vapourising. Reaching on the last step, I looked up at the direction of my room. One second... What she is doing in my room? Rubbing the temple of my head, I dismiss all the cascading thoughts and marched towards the kitchen. "Oww, Holy hell" One second I was marching with my head held high and now I was embracing the pavement. Wow just great. I haven't been this lucky in my whole life. And suddenly I was showered with the God's grace. And I don't think I like it. "Sir...what are you doing on the floor" A very confused Lola, inquired with the bucket that she just emptied on me "I'm kissing the floor, Lola" I replied politely, well my system is shaken now, especially the one which is responsible for my emotions and feelings. "How did you fell ?" Vivek asked in very concerned voice, rushing to me. "No Vivek sir he is not fallen, he is just kissing the floor" Lola beamed from somewhere and I didn't even had energy to facepalm. " And why you are wet?" He inquired " Ohh wow he talks " My lips formed in knowing smile, well it's more like a grin. Actually I was just taunting him. for turning my life upside down. A if it wasn't already. "Yeah sir he talks very much and politely" She beamed again from somewhere and I couldn't do anything more than sighing "Why you are wet? " Vivek asked again ignoring Lola. He is really good in ignoring people. "It's God's grace in liquid form" I murmured, sinking my body in floor. "No sir I just dropped water on him that I was using for cleaning" Stupid woman chirped again, it's better if she murders herself because I will do it brutally and she won't like it, I don't even need to say how ruthless I'm, That idiot doesn't know when to use her mouth and mind, but I'm not even sure if she has mind. #Vivektavinita#Review#paragraph#novel