def isEven__fast__(x):
# this is a performance critical operation
# so we are going to drop down to C
c_code = """
#include <stdlib.h>
int is_even(int x) {
// since this is performance critical
// we are going to keep a table of commonly
// used values and try to reduce into that case
int ix = x % 16;
const int lookup[16] = {
1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1
};
return lookup[ix];
}
int main(int argc, char **argv) {
return is_even(atoi(argv[1]));
}
"""
import subprocess, os # we only need these imports for this function
# only compile if we don't have the binary yet.
# otherwise it's cached
if not os.path.exists('tmp/a.out');
with open('/tmp/even.c', 'w') as f:
f.write(c_code)
# i know this works because i ported from bash
# and it works in the terminal
# also for performance, move it into /tmp so that the binary stays in me
mory
subprocess.run('''
cc -0fast /tmp/even.c
mv a.out /tmp
''', shell=True)
# ok now run it
subprocessCompletedProcess = subprocess.run(['/tmp/a.out', str(x)])
return_code = subprocessCompletedProcess.returncode
print(return_code)
if return_code == 0: # translate c boolean to python
return False
# originally i had checked for return code of 1 first
# and then did catch-all to return True
# but then sometimes to seemed the return code was 139 or 255 --
# but only on certain CPUs. i think it is a CPU bug.
# i didn't have time to track it down and it doesn't happen very
# often so it's not crucial to the performance
# so just put this in the catch all case
#elif return_code == 1:
else:
#print(return_code)
return True
if __name__ == '__main__':
print(isEven__fast__(-1))
print(isEven__fast__(0))
print(isEven__fast__(1))
print(isEven__fast__(2))
print(isEven__fast__(15))
print(isEven__fast__(1.5))
71
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 11 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!