Time taken

Why there is a execution time difference between languages … like for example a code takes 1 sec in C++… Where as the same code in python takes 5 sec …why so ??

Again the time constraint in the question will be 1 sec … I always come across TLE error…

Python is inherently different from C++ - when you write a C++ program, your code gets converted into another language (binary/machine code) that a machine can understand. This is called compilation. The computer can execute this piece of code EXTREMELY fast - since this is basically the native language that the machine can understand. Python on the other hand does not do this directly. It looks at a code, reads a line, converts that to the machine code, and then gets executed.

So what’s the difference? You’d only need to compile your C++ code once and you can execute the machine code multiple times. Python would need to look at your source code every single time it is getting executed.

This process of reading the source file and generating the machine code takes a significant amount of time. On the other hand, when you use C++, (to the best of my knowledge) the compilation time is not counted towards the execution speed of your code. This is why many competitive coders prefer C++ over Python.

Apart from this, there are a few language-specific things like operations on immutable objects in Python. For instance,

This code in C++
string s = "abcde";
s += "f";

would be much faster than

This code in Python
s = "abcde"
s += "f"

Appending to a string in C++ would take O(1) time whereas doing the same thing in Python would take O(n) time. This will make a very huge difference in the execution time - much more than the compiled/interpreted execution time discrepancy.

4 Likes

Thanks for Clearing my Doubt …!!