Python导入代码需要很长时间才能运行...为什么?

时间:2018-04-11 20:58:41

标签: python performance time

以下是我导入另一个文件的一个python文件中的代码...

function removeUrl() {
    var theUrl = document.getElementById('url-input').value;
    chrome.storage.sync.get(null, function(result, error) {

        // Checks if the array (urlList) exists:
        if ('urlList' in result) {
            var theList = result['urlList'];

            // Checks if the url that will be deleted is in the array:
            if (theList.includes(theUrl)) {
                chrome.storage.sync.remove(theUrl);
                chrome.runtime.reload();
            }
        }
        // Error handling goes here
    });
}

我使用上面的代码,然后将其导入另一个python文件......

class Crop():
    def water(self):
        print('not')

    def harvest(self):
        print('not')

    def __init__(self):
        self.height = 0
class Corn(Crop):
    def water(self):
        self.height = self.height + 2

    def harvest(self):
        if self.height >= 9:
            return 1
        else:
            return 0
class Wheat(Crop):
    def water(self):
        self.height = self.height + 1

    def harvest(self):
        if self.height >= 5:
            return 1
        else:
            return 0
class Irrigator():
    def __init__(self, load):
        self.load = load

    def irrigate(self, field):
        while self.load > 0:
            self.load = self.load - 1
            field.rain()

但由于某种原因,代码运行大约需要2到3分钟。我相信后面的代码发布有问题。如果有人有解决方案,请知道!

1 个答案:

答案 0 :(得分:0)

更有效的设计是不将每个工厂建模为单独的实例。就目前而言,您在田地的每个植物上执行完全相同的操作。只需给Field一个尺寸属性和一个裁剪属性,从而为每个场只建模一个工厂,并按尺寸乘以任何尺寸相关的输出。

有些事情如下:

class Field():
    def rain(self):
        self.crop.water()

    def __init__(self, size, crop):
        self.size = size
        self.crop = crop()

class Combine():
    def harvest(self, field):
        quantity = field.crop.harvest() * field.size
        return quantity