+ 2
Which is better and faster?
Which is better and faster when working with a string, convert everything into a string https://code.sololearn.com/cDlhkNf5a3VS/?ref=app , using format() method https://code.sololearn.com/cF0IyJMWs0Vg/?ref=app , or C-style formatting https://code.sololearn.com/cof5apu7Eqn6/?ref=app ? And why???
7 ответов
+ 6
It seems that C-style format is fastest:
https://code.sololearn.com/cXcKCUuMmTUd/?ref=app
+ 4
You can make speed tests using timeit:
import timeit
timeit.timeit("x + x", setup="x = 2", number=10000)
Where "x + x" is a script executed 10000 times and the total runtime will be returned in seconds.
"x = 2" was executed only once in the beginning and will be ignored from the total runtime.
+ 4
Thanks a lot 😊
+ 3
Seb thes: I cant understand ur explanation about timeit.Is this about python?And it is default library in python?
+ 2
Prasetya I don't know. I very rarely use C-style format, I self prefer the format method because it is very readable to use, more readable than using string concatenation such as str(x) + string + str(y).
You might be interested in builtin function repr, which often does the same thing than the str constructor, repr is often half faster than str.
str(5) -> '5'
repr(5) -> '5'
str('b') -> 'b'
repr('b') -> '\'b\''
+ 1
Hepziba janet Timeit is a module from the standard library.
It has a method with same name as the module (timeit), which can take 3 arguments.
In:
timeit.timeit(stmt=a, setup=b, number=c)
where:
c is a positive integer.
a is a string including any Python script, such as "print(\"knight\")", this script will be repeated c times. And the timeit method will return the total time took for a to be ran c times as float.
b is also a string of a Python script, but it will only be ran once in the beginning. This is good for example function definitions.
0
Seb Thes, is it possible to implement it in more complex code and produce different results, for example c-style is slower this time...
Or what you are tested is absolute (if simple code c-style format is the fastest, then automatically in the more complex code, c-style is still the fastest)
I know, bad grammar, sorry