Skip to content

Commit 43d61e3

Browse files
committed
Add divmod_threshold.py script.
1 parent 68b1737 commit 43d61e3

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

Objects/longobject.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4127,7 +4127,7 @@ l_divmod(PyLongObject *v, PyLongObject *w,
41274127
"schoolbook" division is linear-time so don't use in that case.
41284128
These limits are empirically determined and should be slightly
41294129
conservative so that _pylong is used in cases it is likely
4130-
to be faster. */
4130+
to be faster. See Tools/scripts/divmod_threshold.py. */
41314131
return pylong_int_divmod(v, w, pdiv, pmod);
41324132
}
41334133
#endif

Tools/scripts/divmod_threshold.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#!/usr/bin/env python3
2+
#
3+
# Determine threshold for switching from longobject.c divmod to
4+
# _pylong.int_divmod().
5+
6+
from random import randrange
7+
from time import perf_counter as now
8+
from _pylong import int_divmod as divmod_fast
9+
10+
BITS_PER_DIGIT = 30
11+
12+
13+
def rand_digits(n):
14+
top = 1 << (n * BITS_PER_DIGIT)
15+
return randrange(top >> 1, top)
16+
17+
18+
def probe_den(nd):
19+
den = rand_digits(nd)
20+
count = 0
21+
for nn in range(nd, nd + 3000):
22+
num = rand_digits(nn)
23+
t0 = now()
24+
e1, e2 = divmod(num, den)
25+
t1 = now()
26+
f1, f2 = divmod_fast(num, den)
27+
t2 = now()
28+
s1 = t1 - t0
29+
s2 = t2 - t1
30+
assert e1 == f1
31+
assert e2 == f2
32+
if s2 < s1:
33+
count += 1
34+
if count >= 3:
35+
print(
36+
"for",
37+
nd,
38+
"denom digits,",
39+
nn - nd,
40+
"extra num digits is enough",
41+
)
42+
break
43+
else:
44+
count = 0
45+
else:
46+
print("for", nd, "denom digits, no num seems big enough")
47+
48+
49+
def main():
50+
for nd in range(30):
51+
nd = (nd + 1) * 100
52+
probe_den(nd)
53+
54+
55+
if __name__ == '__main__':
56+
main()

0 commit comments

Comments
 (0)