Блог пользователя SoleProprietor

Автор SoleProprietor, история, 16 месяцев назад, По-английски

I have two almost identical submissions getting a substantial difference in execution time:

TLE submission uses variable MOD inside the main function:

def main():
    MOD = 998244353  # local var
    ...
main()

and the AC submission uses variable MOD outside:

MOD = 998244353 # global var
def main():
    ...
main()

Any idea what causes such a difference in performance?

  • Проголосовать: нравится
  • +4
  • Проголосовать: не нравится

»
16 месяцев назад, # |
  Проголосовать: нравится +5 Проголосовать: не нравится

Maybe some experienced Python users like pajenegod can chip in?

»
16 месяцев назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

I submitted, it got accepted both times. The only thing I can think of is this, locally, the MOD variable keeps getting reinitialised for every test case, but globally, it is set once.

The one with MOD inside got 1794ms The one with MOD outside got 1294ms

»
16 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

I guess it could be related to what we have in C++ when defining a constant. Compiler knows we're not gonna change it and apply some specific optimizations based on this fact. And if so — the only question why Python cannot figure out the same thing for local variable.