Python OPTIMIZATION Trick!!

Поділитися
Вставка
  • Опубліковано 28 вер 2024

КОМЕНТАРІ • 889

  • @TheCircuitProject
    @TheCircuitProject 10 місяців тому +3129

    Another alternative is to create a default parameter for the function.

    • @Schecterbaby
      @Schecterbaby 10 місяців тому +61

      I was just about to ask this. Thanks for pointing this out.

    • @shreehari2589
      @shreehari2589 10 місяців тому +12

      Can you give an example

    • @beepbeepgamer1305
      @beepbeepgamer1305 10 місяців тому +1

      ​@@shreehari2589def func_name(local_var):
      when using function in main code
      func_name(global_var)

    • @fres621
      @fres621 10 місяців тому

      ​@@shreehari2589def func(local_var = 10) You can call the function with a custom local var or use 10 as default if none specified

    • @zimzimph
      @zimzimph 10 місяців тому +122

      ​​@@shreehari2589I think they mean pass the global_var as a parameter like def function(local_var): and then pass global_var when you call the function

  • @nikkehtine
    @nikkehtine 10 місяців тому +252

    ... or just pass it to the function as an argument, not only more efficient but also way easier to read

    • @seriouslyWeird
      @seriouslyWeird 9 місяців тому +4

      This doesn't have to semantically make sense at all

    • @vulpritprooze
      @vulpritprooze 8 місяців тому +11

      kinda annoying to keep track of the variables and has to unnecessarily place arguments everytime u call the function

    • @Rudxain
      @Rudxain 7 місяців тому +6

      This is common in Pure Functional Programming

    • @4ngelf
      @4ngelf Місяць тому +2

      ​@@vulpritproozeSo, you can set default parameters

  • @thomquiri9860
    @thomquiri9860 10 місяців тому +3570

    best python optimization trick: switch to another language

    • @lobotomy-victim
      @lobotomy-victim 10 місяців тому +451

      thanks to this trick I managed to get a 50000% performance increase!

    • @sanchogodinho
      @sanchogodinho 10 місяців тому +43

      I switched to NodeJS and then bun.sh!

    • @thomquiri9860
      @thomquiri9860 10 місяців тому +73

      @@sanchogodinho lmaooo, yeah great... optimization I guess

    • @firstnamelastname2775
      @firstnamelastname2775 10 місяців тому +241

      Thank you❤I started learning binary code😍😍😍🥰🥰😍

    • @thomquiri9860
      @thomquiri9860 10 місяців тому

      @@firstnamelastname2775 nice, congratulations :)

  • @PedroHenrique-qh3bl
    @PedroHenrique-qh3bl 7 місяців тому +2

    def func(size, mult):
    return mult * ((size**2 - size) / 2)
    print(func(1000, 10))
    then add some math :p

  • @mickaeldelattre7609
    @mickaeldelattre7609 4 місяці тому +3

    No, Python does not check locally then globally. Python knows what is local and what is global at compile time. The difference is that globals is a dict, locals is an array, so local access is direct indexing vs dict look up. You can have a look at disassembly, when python determines the variable is local it uses LOAD/STORE_FAST, vs LOAD/STORE_NAME. The name is quite explicit which is more efficient.

  • @rahul_chilukamari
    @rahul_chilukamari 22 дні тому

    May I know how you have produced the graph of performance.
    I would highly appreciate if you can create shorts or a detailed video on this.
    I would like to test few other functions and Optimizations for personal use.
    Thanks in advance.

  • @lolcat69
    @lolcat69 4 місяці тому +1

    This problem is the same in every interpreted programming language ( it doesn't affect performance on compiled langs cuz this only happends while compiling, not when running )

  • @GGysar
    @GGysar 8 місяців тому +2

    If you want fast code, don't use python. No, don't optimize your python code, write anything that has to be fast in C and use pyhton for things that don't have to be fast.

  • @videos4mydad
    @videos4mydad 2 місяці тому

    also lookup the phrase 'premature optimization'
    make code harder to read for dubious gains

  • @crispy.caesus
    @crispy.caesus 9 місяців тому +1

    well but actually you don't use the global variable in the first place

  • @rikeshacharya1600
    @rikeshacharya1600 10 днів тому

    Insted of doing that just assign a variable inside the loop.😊

  • @sirbobbyuk
    @sirbobbyuk 3 місяці тому

    Thanks for that, im learning Python coding, so it will help me in improving coding skills

  • @vanlepthien6768
    @vanlepthien6768 4 місяці тому +1

    If you had an (inexplicable) reason to make the variable global, you wanted it updated within the function.

  • @click9000
    @click9000 9 місяців тому +2

    Interesting. Didn't know it impacts performance that much.

  • @somedooby
    @somedooby Місяць тому

    It would be more optimal to calculate the answer rather than iterate. The sum from 1 to N is N*(N+1)/2. So your code could be changed to
    global_var * N * (N+1)/2.

  • @a.j.outlaster1222
    @a.j.outlaster1222 4 місяці тому

    This is actually useful, I'll try to keep it in mind.

  • @NuclearShadowYT
    @NuclearShadowYT 2 місяці тому +1

    Your first mistake was using python if you're worried about performance

  • @rafaelmesaglio1399
    @rafaelmesaglio1399 2 місяці тому

    This is the exact type of thing a compiler would optimize for.... oh wait

  • @geoafrikana
    @geoafrikana 10 місяців тому +1

    I do this a lot when building a data-cleaning function. It also avoids mistakingly corrupting the global variable.

    • @sarsoar
      @sarsoar 10 місяців тому +6

      If you try writing to global_var it will create a local instance precisely to avoid corrupting it. You have to use the global keyword to specify global_var is global and be able to write to it. But really in the example in the video global_var should just be a parameter that is passed in. 99% of the time globals issues can be solved by just not using them and refactoring your code appropriately or starting with best practices from the beginning.

  • @C_itsNemo
    @C_itsNemo 6 місяців тому

    Where’d this guy go I like these videos

  • @JohnFerrier
    @JohnFerrier 9 місяців тому

    If you’re good at python, you should do the multiplication after the summation, since they’re separable.

  • @thedapperfoxtrot
    @thedapperfoxtrot 7 місяців тому

    The synthwave theme extension though. My man 👌

  • @kobekapoor
    @kobekapoor 3 місяці тому

    Can you do a video on how you test performance like that?

  • @LOBOTOMYtv
    @LOBOTOMYtv 4 місяці тому

    Man being new to Python and new to coding just sounds like an awful time. Coming into python with years of statically typed OOP these are just things I do automatically lol

  • @popcultureprogrammer2171
    @popcultureprogrammer2171 3 місяці тому

    The best optimization trick for Python is to write the performance-heavy bits in C++ and use Python as a frontend

  • @hevad
    @hevad 7 місяців тому

    Putting aside the fact that the use of global variables sticks out like a sore thumb, this looks like an optimization that the runtime should do for me, and not have me jumping hoops to skirt around the runtime's lousy performance.

  • @KonDima123
    @KonDima123 9 місяців тому +1

    I think it is much better to make function with this 'global varible' as argument. Using global variables in functions is bad practise, because it makes functions less portable (you can't just take this function and place it in another program or file, because it may doesn't have this variable in it)

    • @HansBezemer
      @HansBezemer 5 місяців тому

      Better - when writing non trivial programs, it's often hard to avoid globals - unless you want to make the call graph a complete mess. If you're determined to kill all globals, you might want to malloc() a singleton (a struct) containing all of them (so you can re-enter the function without side effects) and pass it down all the way - even if you don't use it. That way if you change a function so it requires the use of such singleton, it's there. You might get a few warnings, but it works - and it makes maintenance less of a pain in the neck. BTW, always initialize your global vars in a separate function. You might be in for a surprise if you call it multiple times.

  • @johnvine5731
    @johnvine5731 6 місяців тому

    When nanoseconds make a difference.

  • @abdullahqureshi7165
    @abdullahqureshi7165 13 днів тому

    just write "global global_var" before using the global_var in function

  • @Hallilo
    @Hallilo 7 місяців тому +2

    Alternative: use C

  • @fedyfausto
    @fedyfausto 9 місяців тому

    This is the why you must use memory managed languages such as c/cpp or go

  • @soniablanche5672
    @soniablanche5672 6 місяців тому

    wow didn't know the python interpreter was so bad, this should be optimized automatically

  • @TheKilledDeath
    @TheKilledDeath 9 місяців тому +188

    Sorry this is just very bad. Really, really, really bad. NEVER teach people how to optimize the use of global variables. Teach them how to avoid them alltogether.

    • @Suekru3
      @Suekru3 8 місяців тому +6

      Right? I thought he was going to say to pass it into the function as a parameter, since he said “new to python” but I guess not lol

    • @bitzero000
      @bitzero000 7 місяців тому +1

      look it's bad practice but people use globals and sometimes they provide value too

    • @olivierdulac
      @olivierdulac 7 місяців тому +2

      Especially his changes also changed the whole program's behaviour as Global_var is no longer updated.

    • @NickMak-m2c
      @NickMak-m2c 6 місяців тому

      Question, how is he even getting the global variable to work in his function without write
      global (var_name)
      at the top of the function?

    • @JackySupit
      @JackySupit 5 місяців тому

      so you never use a global variable / constant in your code?

  • @Wyrmver
    @Wyrmver 4 місяці тому

    btw for that function couldn't you do some math trickery

  • @nagatosmith1158
    @nagatosmith1158 2 місяці тому

    Thanks!

  • @ankushbhagatofficial
    @ankushbhagatofficial 10 місяців тому +27

    Which program you used to see performance difference?

    • @santiagoavalos3637
      @santiagoavalos3637 10 місяців тому

      Came here to ask the same thing 🤔

    • @andgnd3674
      @andgnd3674 10 місяців тому +1

      looks like seaborn

    • @smaaack
      @smaaack 10 місяців тому +1

      Likely a python library like seaborn or matplotlib

    • @peter9477
      @peter9477 9 місяців тому

      See module timeit

  • @luis96xd
    @luis96xd 7 місяців тому

    Thanks for the tip

  • @kaxun
    @kaxun 9 місяців тому

    I taught im the only one who using synthwawe 84 material theme

  • @hexailon
    @hexailon 4 місяці тому

    Don't do that. First, you should avoid using a global variable.
    But let's assume you really need to. Then use the "global" keyword inside of you scope to indicate the interpreter to look directly into the global scope ti retireve the variable. You should also checkout the "lonlocal" keyword, having the same effect but instead of targeting the global scope, it targets the direct upper one.

  • @arlokleijweg5970
    @arlokleijweg5970 5 місяців тому

    1. You shouldn't be using globals anyway.
    2. If you need performance, you shouldn't use Python.

  • @gregoryg72
    @gregoryg72 8 місяців тому

    And that's exactly why interpreted languages suck. The compiler would do that optimization for you in any decent compiled language.

  • @reactoromg3906
    @reactoromg3906 7 місяців тому

    Could you make a video how I could make a text document where there is a list and in my python program I want a list that is the list of the text document. I would really appreciate it. Thanks for the helpful videos.

  • @sumit5294
    @sumit5294 8 місяців тому

    Well , this technique won't help when we actually need to update the value of the global variable or it should be mentioned explicitly before return to reassign the local value to global variable.
    Nice trick btw

  • @bradenhelmer9795
    @bradenhelmer9795 9 місяців тому

    Or just don’t use globals, only if they’re constant. Python doesn’t specifically implement constants but you can denote them with capitalization.

  • @ZeroChronicles01
    @ZeroChronicles01 8 місяців тому

    I got a question, how would you switch an item between two dictionaries or lisits? Lets say an person between "working" and "on break" lists?
    One idea i had was this.
    People = [people names here]
    Working = [people:]
    On break=[:people]

  • @paulimriss
    @paulimriss 4 місяці тому

    another alternative is to not use python in iterative tasks.

  • @kellybmackenzie
    @kellybmackenzie 6 місяців тому

    Remember friends: Premature optimization is the root of all evil. Benchmark before you optimize.

  • @Wyklepheph
    @Wyklepheph 6 місяців тому

    Best python optimization is switching to Nim

  • @AMTunLimited
    @AMTunLimited 4 місяці тому

    There's no way the interpreter doesn't catch that, or maybe I'm just too used to real compilers. I'll test it

  • @d1kkop
    @d1kkop 4 місяці тому +1

    Python for CPU intensive tasks...

  • @therealvbw
    @therealvbw 8 місяців тому

    Another W for compilers

  • @-wx-78-
    @-wx-78- 3 місяці тому

    Alias everything… unless you have to update. 😉

  • @perolavroviski5405
    @perolavroviski5405 2 місяці тому

    What is your theme it is veryy veryyy beautiful

  • @anamoyeee
    @anamoyeee Місяць тому

    There's no way this works. Scopes of variables are determined on compile time?

  • @eldebtor6973
    @eldebtor6973 7 місяців тому

    well actually, you should pass it as an argument

  • @ght0076
    @ght0076 8 місяців тому

    is this new? i thought global variables were limited to the outer scope unless you used the global key.

  • @maruftim
    @maruftim 8 місяців тому

    cant wait for the livestream

  • @Tenkite001
    @Tenkite001 2 місяці тому

    But don't it does the same when you define it ? Search locally, then outside ?

  • @СергейБолдин-в9м
    @СергейБолдин-в9м 8 місяців тому

    Why is it searching like that? Why doesn't Python know beforehand the function's local variables?

  • @bobmike2373
    @bobmike2373 5 місяців тому

    doesnt that also make a copy of the global var? like any changes to the global var wont be kept outside of the function's scope

  • @ぐうたらぼっち-e7t
    @ぐうたらぼっち-e7t 8 місяців тому

    Is it just me feel anxiety when there isn't an empty line at the end of file?

  • @misogear
    @misogear 8 днів тому

    It's mind boggling if this is not optimized automatically 😂😢😢😢

  • @pendragonscode
    @pendragonscode 2 місяці тому

    function parameters: exists

  • @dastagirwajahat
    @dastagirwajahat 7 місяців тому

    I was using this for convenience but it is optimization aswell 😅

  • @levimatheri7682
    @levimatheri7682 3 місяці тому

    What font and theme are you using?

  • @eduardmart1237
    @eduardmart1237 Місяць тому

    How did you make performance graph?

  • @benshapiro9731
    @benshapiro9731 Місяць тому

    This is not true. Bariable scope bindings occur at compile time for python (aka before the interpreter runs the byte code). By default, python does not perform those successive lookups you describe. Rather, if a global variable or a variable in the closure of a function is referenced, the interpreter will produce byte code referencing the variable in the correct location. So this ultimately does not matter.

  • @jakeharrison505
    @jakeharrison505 Місяць тому

    Solution: don’t use for loops in python

  • @FundamSrijan
    @FundamSrijan 7 місяців тому +1

    Bro , I want to take input from the user . But the input should be a number b/w 1 and 62 , what should I do to remove errors and take the input

    • @Nip403
      @Nip403 5 місяців тому +1

      Either regex or try-except int(input()) or .isdigit string method, then if/assert converted_to_int in range(1, 63)

    • @FundamSrijan
      @FundamSrijan 5 місяців тому +1

      @@Nip403 will definitely try

    • @briannormant3622
      @briannormant3622 5 місяців тому

      ​@@Nip403 advising the use of regex for someone new to programming is mean.
      Python definitely has a built-in function to check if a str is a valid number before converting.

  • @MF_RAZVAN
    @MF_RAZVAN 10 місяців тому

    I need this theme

  • @TESFan791
    @TESFan791 2 місяці тому

    It still has to find the global variable information tho.. so it still goes up to look for it right?

  • @overbored1337
    @overbored1337 10 місяців тому +23

    Optimizing python is like polishing a turd

    • @ThisShitWontWor
      @ThisShitWontWor 7 місяців тому

      Yeah but I guess no fucking one use it for performance anyway 😂

    • @drewsarkisian9375
      @drewsarkisian9375 5 місяців тому

      As usual, can't let folks alone who like Python (for all its quirks) and actually add some useful information. "Thanks" for sharing your "wisdom".

    • @overbored1337
      @overbored1337 5 місяців тому

      @@drewsarkisian9375 Its the Duplo of programming

    • @HansBezemer
      @HansBezemer 5 місяців тому

      @@drewsarkisian9375 There's nothing wrong with using Python - but accept that "optimizing" it is useless. If you want raw performance, accept you have to use another language.

  • @CaptMirage
    @CaptMirage 3 місяці тому

    how did u do the graph? just used data to create it or some website or smth

  • @Norfirio
    @Norfirio 2 місяці тому

    Use numpy or some library written in C instead of native Python
    If that's not enough then ditch Python; you're using the wrong tool for the job

  • @hassanahmed7326
    @hassanahmed7326 9 місяців тому

    Please can you show us how you check the performance fir both options

    • @progamer1125
      @progamer1125 9 місяців тому +1

      you can run the function 10k times and store the start and finish time with time.perf_counter()

  • @XxZeldaxXXxLinkxX
    @XxZeldaxXXxLinkxX 8 місяців тому

    You guys know he's probably giving out bad advice so everyone complains in the comment and gets him more engagement rating on youtube right? (you're welcome guy)

  • @aritramondal6942
    @aritramondal6942 8 місяців тому

    Those two runs with 30% increase:🗿

    • @vaolin1703
      @vaolin1703 7 місяців тому

      It’s because of background noise

  • @vidiohs
    @vidiohs 4 місяці тому

    Right that way it already has the variable to access

  • @aneesh1701
    @aneesh1701 10 місяців тому +14

    or you can just say global var_name above the for loop

    • @ZeroSpawn
      @ZeroSpawn 10 місяців тому

      Well if that Global variable is needed somewhere else one would have to dive into the for Loop to get the value.

    • @aneesh1701
      @aneesh1701 10 місяців тому +3

      @@ZeroSpawn what are you saying? if you want a function to access a variable declared at a global scope you can add the line "global variable_name" below the function definition to make it accessible without redefinition

    • @nigh_anxiety
      @nigh_anxiety 10 місяців тому +2

      Adding the global keyword specifically tells Python to WRITE to that global variable if you try to assign to that name instead of the local namespace, so if you want to ensure that your function code can't modify the global variable, that's a bad way to go.

  • @larakayaalp1676
    @larakayaalp1676 3 місяці тому

    yk python is slow when it takes 7% of the performance to access a variable out of scope

  • @kevinhlavaty8941
    @kevinhlavaty8941 7 місяців тому

    This is like putting lipstick on a pig

  • @giansirait9631
    @giansirait9631 5 місяців тому

    How to show that result test?

  • @fullstack_journey
    @fullstack_journey 5 місяців тому

    .. WRITE PURE FUNCTIONS! :')

  • @richardsinclair7661
    @richardsinclair7661 9 місяців тому

    Does anyone know this theme? I really like it.

  • @complexity5545
    @complexity5545 9 місяців тому +2

    First optimization, move to C or C++ or Go.

  • @mubris9705
    @mubris9705 7 місяців тому

    Rumors say function parameters exist.

  • @linuxguy1199
    @linuxguy1199 9 місяців тому +3

    One alternative I really like, is just using C.

  • @yaseemanac
    @yaseemanac 6 місяців тому

    Good one.

  • @lOmaine777
    @lOmaine777 10 місяців тому +2

    What if I want to make changes to the global variable? I'll have to use global or globals() right?

    • @b001
      @b001  10 місяців тому

      Right. If you want to make changes to the global_var using the for-loop, you could still use this method and after the for-loop is finished, re-assign the global_var with the new local_var. This would prevent searching globally each for-loop iteration.

  • @YuraSuper2048
    @YuraSuper2048 5 місяців тому

    just use rust if you need speed😊

  • @Andrumen01
    @Andrumen01 9 місяців тому

    Or just use the "global" keyword inside and it will create a reference in the function's cache...

    • @peter9477
      @peter9477 9 місяців тому

      No it will not. There is no such "cache" and the global keyword merely prevents the compiler from creating a local variable if you re-assign the name.

    • @Andrumen01
      @Andrumen01 9 місяців тому

      @@peter9477 Python DOES have a cache! Otherwise how will it find the reference to the functions? It does cache variables, how do you think it invokes and references them? Why bother using "global" then? Well, to know that it's the global variable that you're using, i.e., set a reference to it when it appears -> a cache a reference, a memory slot that points towards the specific variable....

    • @peter9477
      @peter9477 9 місяців тому

      @@Andrumen01 I've been using Python since 1999 and I've never seen any Python expert refer to any of the name resolution stuff as a "cache". Yes, it has namespaces, which you might think of that way, but those aren't caches per any conventional definition of the word. They're just dictionaries. As for how it finds stuff: 1. Locals (which aren't "cached" but compile-time indexed), 2. Module-level globals (a dictionary), and 3. Builtins (a true global namesake, also a dictionary). To the extent that you think of a cache as being any place where things are put and later found... okay, go ahead and call it a cache. I don't think anyone else does though.

    • @peter9477
      @peter9477 9 місяців тому

      By the way, you referred specifically to "the functions cache" yet you were talking about globals, which are absolutely not in a function. The fuzziness in your terminology makes me suspect you're using these words imprecisely, without strong meanings, in which case please just trust me: nobody calls these things "caches" in Python.

    • @Andrumen01
      @Andrumen01 9 місяців тому

      @@peter9477 I do...so....there is somebody who uses it. Imprecise, in your opinion...or somebody elses...not mine!

  • @nandurstudio
    @nandurstudio 8 місяців тому

    hi, what font did u use? ty

  • @mayurahir9340
    @mayurahir9340 7 місяців тому

    How to check performance results can u tell me ?

  • @HansBezemer
    @HansBezemer 5 місяців тому

    Best perfomance boost - use another language.

  • @ThiagoOliveira-wp6lp
    @ThiagoOliveira-wp6lp 7 місяців тому

    I stopped at GLOBAL VARIABLE

  • @kunalsoni7681
    @kunalsoni7681 10 місяців тому

    helpful 💯😌

  • @hiderikanzaki7516
    @hiderikanzaki7516 Місяць тому

    Another way is to stop using global variables

  • @helligusvartproject
    @helligusvartproject 6 місяців тому

    Nice one

  • @SahilSoni-x3g
    @SahilSoni-x3g 9 місяців тому

    Sir can you please explain.which one is better make a program normally or using def() function to create a program.which one is more optimized😊.so plz reply 🙏

  • @justinesalazar2142
    @justinesalazar2142 7 місяців тому

    what's the name of the application? newbie here