SoleProprietor's blog

By SoleProprietor, history, 22 months ago, In English

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?

  • Vote: I like it
  • +4
  • Vote: I do not like it

»
22 months ago, # |
  Vote: I like it +5 Vote: I do not like it

Maybe some experienced Python users like pajenegod can chip in?

»
22 months ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

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

»
22 months ago, # |
  Vote: I like it 0 Vote: I do not like it

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.