1
\$\begingroup\$

I have written this module that takes input of configuration of multiple lines with first item as available storage and remaining are the process at different rate using sys.stdin .

#! /usr/bin/python

""" this script calculates the time remaining for available storage to get filled up.
"""

import sys

def time_to_meltdown(proc_r, available_storage):
    """
    this functions caclulates the time it will take to full the available disk space
    by n number of proceses by the rate of 1 byte after every d(p_i) seconds.

    :param list proc_r: number of process with constant but different rate memmory consumption
    :param int available_storage: total amount of free storage available on the farm.

    :return: time in seconds taken by n process to fill up the storage
    :rtype: int
    """
    mem = 0 # Initial consumption
    timeTaken = 0
    while mem < available_storage:
        timeTaken += 1 # increament each second by 1
        mem = 0
        for v in proc_r:
            mem += timeTaken // v
    return timeTaken


def main():
    """ this function builds data from the input and pass it
        to function that calculate time it will take to for
        available storage to get filled.
    """
    input_data = sys.stdin.read()
    config_lines = input_data.split("\n")
    for line in config_lines:
        if line:
            data = [int(data) for data in line.split() if data]
            available_storage = data[0]
            pr_i = data[1:]
            print "{} processes will take {} seconds to fill storage".format(len(pr_i), time_to_meltdown(pr_i, available_storage))

if __name__ == "__main__":
    main()

Please review the code for optimal performance.

When I run this code:

        while mem < available_storage:
        timeTaken += 1 # increament each second by 1
        mem = 0
        for v in proc_r:
            mem += timeTaken // v
    return timeTaken

above lines take quite substantial amount of time for long list of processes.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ As suggested here, use binary search. \$\endgroup\$ – vnp Aug 7 '18 at 20:36
  • \$\begingroup\$ Yes I writing binary search. \$\endgroup\$ – Ciasto piekarz Aug 9 '18 at 6:14
2
\$\begingroup\$

You may be able to speed up the body of the loop using the sum function & list comprehension:

mem = sum( timeTaken // v for v in proc_r )

But the real speed up won’t come until you realize you can compute a lower limit for timeTaken, and begin looping starting from that value, instead of from zero.

\$\endgroup\$
1
  • \$\begingroup\$ I will write binary search and post updated. \$\endgroup\$ – Ciasto piekarz Aug 9 '18 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.