Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm running a python program that finds all the prime numbers. Is it possible to allocate all the computer's power to this single task. By using all the 4 cores that my processor have?
Thanks!
p.s. I'm using Linux of course!
The code I'm using is:
nextCheck = time.time() + 60
primesFound = 0
while 1:
if isPrime(toTest):
open("primeList.txt", "a").write(str(toTest)+"\n")
primesFound += 1
toTest += 2
if (toTest+1) % 1000 == 0:
if time.time() >= nextCheck:
print "Average speed: " + str(float(primesFound)/((time.time()-nextCheck)+60)) + "/s"
primesFound = 0
nextCheck = time.time() + 60
Use multiprocessing. If you are using CPython, only one thread at a time can execute Python bytecode so using threads isn't that much help.
If you can e.g. write a simple function to test a number, you can use a multiprocessing.Pool object's map() method to apply that function to a list of numbers.
You can also assign a higher priority to your Python process using nice:
nice -n -20 python app.py
... that will help, but will not guarantee that you are squeezing out all the power from your computer.
For that code, the best you can try is:
do not write numbers directly to an output file and save them in a memory structure,
program an event for not checking all the time about whether you need to print the speed statistics or not,
try to split out in several concurrent tasks the operations performed within function "isPrime" for executing them as separte tasks.
... however, I do not know whether this application worths this effort.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I tried for hours to solve this python riddle in my level of knowledge and I don't know what to write past the thinking part "I need to make tails more frequent by using +1 to something" maybe. The riddle goes like that:
import random
def broken_coin():
if random.random() <= 0.9:
return "Heads"
return "Tails"
using no random source part of the function(which you can't edit), and turn the coin into a standard one: if you print the code the chances for heads will be 50% and the chances for tails will be 50%
thanks early to anyone who commented :)
EDIT: added what was my idea
If I read your problem correctly, you need to provide a method to compensate for the broken coin producing a relatively fair amount of results. With that instead of calling the broken_coin() function every time directly, one could call a function that calls the function and every other time returns the reverse result to the calling function.
After reading the comments about what could or could not be used, I've updated my sample code.
import random
def broken_coin():
if random.random() <= 0.9:
return "Heads"
return "Tails"
def fix_coin(j):
if j == 0:
return broken_coin()
coin = broken_coin()
if (coin == "Heads"):
return "Tails"
else:
return "Heads"
for x in range (100):
print(fix_coin(x %2))
See if this more closely fulfils the spirit of the problem.
Regards.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I would like to be able to have a for loop execute different code depending on what 'mode' it is in, but in the name of efficiency not have to check this mode at every iteration. It's easy to do this if you allow these checks:
for i in range(n):
if m == 0:
# execute some code, test whether to update m
continue
if m == 1:
# execute some other code, test whether to update m
But what I would like is if the for loop kept its current mode and carried on unless it was specifically told to change it, to avoid the extra 'mode check' step on every iteration.
Weirdly, the only way I can think to do this is using goto statements, which I know can't be the answer!
i = 0
# start line for mode 1
# execute some code
i += 1
# test what mode to be in next, goto that line
# start line for mode 2
# execute some other code
i += 1
# test what mode to be in next, goto that line
# stop when you're at n
Hopefully you can see that these two theoretical programs achieve roughly the same thing, unless I've misunderstood somehow. However, the second one does not have to test its mode after every increment of i, because the action of testing what mode to be in next also puts it at the correct place to execute the right bit of code for that mode. The first one runs a test and updates m on one iteration, then has to test m on the next iteration to check what to do next.
I think that my theory is right and that a) these things are different and b) this should be possible (i.e. you don't need to do the 'double test'). If so, I would like some help implementing it in a neat way in python, please.
You should start by asking if this is a meaningful optimization, or a pointless micro optimization. If your profiling reveals that a significant amount of time is being spent on checking the mode, you can avoid doing so with code roughly structured like this:
while True:
if m == 0:
while True:
# Do stuff here
# Run `break` when the mode changes
pass
elif m == 1:
while True:
# Do stuff here
# Run `break` when the mode changes
pass
The loops can be of any sort - whatever suits your needs. I would also recommend extracting the codeblocks under the if statements into functions that return instead of breaking:
def do_mode_0_stuff():
while True:
# Do stuff here
# Run `return` when the mode changes
pass
def do_mode_1_stuff():
while True:
# Do stuff here
# Run `return` when the mode changes
pass
while True:
if m == 0:
do_mode_0_stuff()
elif m == 1:
do_mode_1_stuff()
In the end I highly doubt this sort of restructuring will lead to any significant performance improvement, so I would go with whatever structure is most clear, elegant, and maintainable.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm creating TUI (Text-based user interface) using print statements, and when I want to return to the 'homescreen' i want the older code to run again.
randbool = True
while randbool:
print('1')
randbool = False
while not randbool:
print('2')
randbool = True
the result im expecting is
1
2
1
2
1
2
....
but it only prints 1, 2 how can I make it run indefinitely?
Not advisable, but:
while True:
print('1')
print('2')
This will print 1,2,1,2,1,2 indefinitely, until your CPU usage is at 100%, and your whole system freezes.
But it will accomplish what you're asking for.
Edit to add: 100% CPU usage demonstrated on an i7 laptop with 16GB RAM on Ubuntu 18.04:
If the value of randbool lets you get in a loop, changing it will stop the loop.
So don't change it for a loop you don't want to stop.
If you want to print 1 and 2 indefinitely, a simpler solution would be:
# loop forever
while True:
print('1')
print('2')
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am running different Python scripts in Linux and I want to see how much time these scripts, I wonder if there is a command in Bash or in Python it doesn't depend to echo or print to the screen how much time it took to run the command. Thanks in advance.
For example the Python script might be :
import subprocess
command = ['sudo', '-S', 'iwlist', 'wlan0', 'scan']
output = subprocess.Popen(command, stdout=subprocess.PIPE).stdout.read()
data = []
for cell_item in output.split("Cell"):
data_item = []
for line in cell_item.split("\n"):
if any(item in line for item in ["ESSID", "Quality", "Pairwise"]):
data_item.append(line.strip())
if data_item:
data.append(data_item)
print data
What I want is to see on the screen under the last line of some code outputs, I want to see there i.e. ; "This Code Lasted 16.363 seconds"
Just put time before any other command or script e.g.:
time sleep 4
gives
real 0m4.003s
user 0m0.000s
sys 0m0.001s
You can change format of the output as well, see man time.
Personally I use:
from datetime import datetime
t1 = datetime.now()
bashCommand = "df -h > space.txt"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
t2 = datetime.now()
total = t2-t1
print total
So based on the comments, the question appears to be "how can I retroactively see how long my previous commands took?" The answer is simple: you can't.
Python does not automatically time itself when it's running code, and all import time will do is give you access to functions to do the timing yourself. If you ever want to know how long something takes, you have to explicitly say so before the fact. After the code is run, I can't think of anything that will go back and determine how long it took to run. I believe you're going to have to do all of your timing again, sorry to say.
Use bash's special variable SECONDS:
SECONDS=0
script.py
echo $SECONDS
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am using notepad++ for writing codes and then seeing output using Windows Power Shell. Now lets say I want to print this...
"Stack Overflow"
But not all at once. First of all it will print S then t then a then c then k then a space and then O ...... ?
So is there any function/method to post the text as we type in old PCs?
If the question is not complete let me know what more information I can provide you.
Update
#uʍop ǝpısdn Yes, you understood my requirement. And many thanks for the answer. :)
Well I didn't know that it calls Emulating text. :)
Here you go:
import time, sys
for letter in "Stack Overflow":
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(1) # that's in seconds, adjust at will
sys.stdout.write('\n')
Why stdout.flush?
Output from a running program is usually buffered (i.e. held waiting) until certain conditions are met. The call to sleep() will not fulfill these conditions, and the text will not appear. By calling flush() after each letter, you force it out.
from __future__ import print_function # only needed for Python 2.x
import random
from time import sleep
def delay_print(s, min_delay=0.1, max_delay=0.8):
for ch in s:
delay = min_delay + random.random() * (max_delay - min_delay)
sleep(delay)
print(ch, end="")
print('')
delay_print("StackOverflow")