I'm working on a program that performs a Monte Carlo simulation of percolating systems (using python). In order to be able to run it from a GUI (tkinter) and to use multiple processes, I've defined the main part of the simulation in a main() function. The thing is, this program being a physical simulation, it takes in many parameters (10+). Some functions called from main() also need a lot of parameters and are called many, many times. For instance, in my main(), I have a generate_wire() function that takes in 8 parameters, such as wires_mean_length, wires_distribution, etc. This one is called millions of times.
Can that affect the efficiency of the program ? Is it something that should be fixed, and if so, how ?
EDIT: The code is basically structured as follow:
def generate_wire("8 parameters"):
"generating a wire according to the parameters"
def main("main parameters"):
for _ in range(nbr_sim):
while True:
generate_wire("8 parameters taken from the main parameters")
"Various calculations"
if percolation is True:
break
if __name__ == '__main__':
"GUI code"
"Run button calls the main function with parameters from GUI entries"
Practically, this will not affect the runtime of the program compared to other design
You can bring all of your arguments into a dictionary or a custom class and pass that around to make the logic clearer
You could hoist the logic in your function directly into the loop, which will allow the lookups to occur less often
More about local variable lookups
def generate_wire_wrapper("8 parameters"):
for _ in range(nbr_sim):
"logic to generate a wire"
"various calculations"
def main("main parameters"):
generate_wire_wrapper("8 parameters taken from the main parameters")
However, improving design will be your real ally here
Instead of calling the same function thousands of times in a loop, consider
.apply
method does this, for example)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.