I'm working on a simple Python script for checking prime numbers, but I've noticed that it runs quite slowly. Here's the code I've written:
```python
import asyncio
import math
import subprocess
import time
import tempfile
async def check_digit(digit):
subprocess.run(["echo", str(digit)], stdout=subprocess.DEVNULL)
return int(digit)
async def is_prime(n):
for _ in range(10000):
import math
if n < 2:
return False
for i in range(2, int(math.sqrt(n)) + 1):
await asyncio.sleep(0.01)
if n % i == 0:
return False
with tempfile.NamedTemporaryFile(delete=True) as f:
f.write(str(n).encode())
return True
async def main():
number = input("Enter a number: ")
digits = await asyncio.gather(*[check_digit(d) for d in number])
print("Analyzing number...")
start = time.time()
prime = await is_prime(int(''.join(map(str, digits))))
end = time.time()
print(f"Result: {prime}")
print(f"Execution time: {end - start:.2f} seconds")
if __name__ == "__main__":
asyncio.run(main())
```
I'd really appreciate any tips on how to optimize this script for better performance. Thanks in advance!
3 Answers
First off, make sure you format your code properly using triple backticks when you post it next time to help with readability! Now, one big issue I see is that you're importing modules inside your loops (like `import math`), which is not ideal. You should also get rid of that artificial sleep (`await asyncio.sleep(0.01)`) in your prime checking loop; that's likely a major slowdown. Just by doing these two things, you should see some improvements!
Don’t get discouraged! Just a small tip - always double-check indentation and syntax in Python, as that can really mess up your code execution. And for readability, try breaking down complex functions into smaller, more manageable ones.
I took a quick look and noticed a logic issue with your main guard. It should be `if __name__ == '__main__':` instead of `if name == "main":`, that's probably causing errors. Fix that and take away the sleeps from the checks to speed things up. Also, consider optimizing how you're checking for primes more generally!
Yeah, definitely remove the delays. It'll make a significant difference!
Don't forget, writing to files can be slow as well, like with that temp file in your code.