amarnathsama's blog

By amarnathsama, history, 4 years ago, In English

My friend and I did problem D(link) from last contest(#723),

His Code

My Code

We both use recursion and a similar-ish method to solve the question yet his code runs 4x faster than mine, normally this shouldn't be an issue since both our codes are comfortably within the time limit, but I was just wondering why there is such a huge difference in the execution time.

Also, sorry if our code isn't very readable.

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

| Write comment?
»
4 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Auto comment: topic has been updated by amarnathsama (previous revision, new revision, compare).

»
4 years ago, # |
Rev. 4   Vote: I like it +3 Vote: I do not like it

You're using endl for a new line but your friend's code uses "\n". I don't really remember the exact reason but endl takes more time so you see a 400-500ms difference for 1e5-1e6 operations.

Edit: Found this statement on gfg — "Writing ‘\n’ characters directly to the stream is more efficient since it doesn’t force a flush like std::endl. Flushing of buffers is an Operating System task. Each time the buffer is flushed, a request has to be made to the OS and these requests are comparatively expensive."

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    ohhhhhhhhh, lol, i guess while trying to check for every small detail, i missed the absolute obvious. Thank you, it works much faster now.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Similiar issue Happens with me all the time. When I use cout/cin the judges give TLE but scanf printf passes the testcases (when input output are in 10^6 order).