ASKSAGE: Sage Q&A Forum - Individual question feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sat, 03 Mar 2018 06:52:14 -0600Is it possible to speed up loop iteration in Sage?https://ask.sagemath.org/question/41375/is-it-possible-to-speed-up-loop-iteration-in-sage/I have a sage code that looks like this:
uni = {}
end = (l[idx]^(e[idx] - 1)) * (l[idx] + 1) # where end in my case is about 2013265922 but can also be much larger
for count in range(0, end):
i = randint(1, 303325737249669131)
if i in uni:
uni[i] += 1
else:
uni[i] = 1
So basically, I want to create very large number of random integers in the given range, check whether the number was already in the dictionary, if yes increment its count, if not initialize it to 1. But, this takes such a long time that it doesn't finish in a reasonable time. Is there any way to speed up this kind of loops in Sage (or Python)?Sat, 03 Mar 2018 05:10:30 -0600https://ask.sagemath.org/question/41375/is-it-possible-to-speed-up-loop-iteration-in-sage/Answer by calc314 for <p>I have a sage code that looks like this:</p>
<pre><code> uni = {}
end = (l[idx]^(e[idx] - 1)) * (l[idx] + 1) # where end in my case is about 2013265922 but can also be much larger
for count in range(0, end):
i = randint(1, 303325737249669131)
if i in uni:
uni[i] += 1
else:
uni[i] = 1
</code></pre>
<p>So basically, I want to create very large number of random integers in the given range, check whether the number was already in the dictionary, if yes increment its count, if not initialize it to 1. But, this takes such a long time that it doesn't finish in a reasonable time. Is there any way to speed up this kind of loops in Sage (or Python)?</p>
https://ask.sagemath.org/question/41375/is-it-possible-to-speed-up-loop-iteration-in-sage/?answer=41378#post-id-41378Using Cython can dramatically improve performance by converting the code to C and compiling it. For example,
%%cython
import random
def run(end):
uni = {}
for count in range(0, end):
i = random.randint(1, 303325737249669131)
if i in uni:
uni[i] += 1
else:
uni[i] = 1
return uniSat, 03 Mar 2018 06:52:14 -0600https://ask.sagemath.org/question/41375/is-it-possible-to-speed-up-loop-iteration-in-sage/?answer=41378#post-id-41378