Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python reliability?
#1
Hello everyone.
I just wrote (well, I would say copy and paste for the most part) a few lines of code as follow in order to test efficiency:
import time
start = time.time()

a = range(100000)
b = []
for i in a:
b.append(i*2)

# a = range(100000)
# b = [i*2 for i in a]

end = time.time()
print(end - start)
as you can see, there are 2 'for' loops, one inside the list (inactive as a comment), the other outside. It's the classical example to display "good" VS "bad" coding method. But here's my issue. I ran both loops in Python 3.7, but the the "good" version is giving 0.0 as result. I tested the same code with Spyder 3 (Anaconda) and it seems working fine with resonable results (one is/should be twice the other).
Could you help me and tell me where I'm making a mistake?
Thank you for your time.

Cheers,

OttoBit
Reply
#2
Use timeit module,then get more than just one run with average time back.
(Jan-30-2019, 06:14 PM)OttoBit Wrote: It's the classical example to display "good" VS "bad" coding method.
Not really some time make a ordinary for loop more sense,
and some time is list comprehensions a better solution,it really depend on the task.

Can do it like this,to not use a function.
import timeit

for_loop = '''\
a = range(100000)
b = []
for i in a:
    b.append(i*2)
'''

list_comp = '''\
a = range(100000)
b = [i*2 for i in a]
'''

print(timeit.Timer(stmt=list_comp).timeit(number=1000))
I did knew the result before i ran it,that list comprehensions would be slightly faster.
Output:
13.863839585 # for_loop 8.8190991 # list_comp
Reply
#3
Slightly faster?

Almost half the time!

By the way, my question remains. I cannot have the result for the list. For me Python gives '0.0' (null) as result.
With Anaconda and Spyder, instead, everything seems fine. Is it a compatibility issue? Can those two run in the same system?
With 'timeit' all goes well, but mind the results. Your (snippsat) method give results in seconds, while mine are between 20 and 10 milliseconds (or better if you have a more powerful machine than mine). So 'timeit' is not a better solution for this case.
Thank you.

Cheers,

OttoBit
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020