EBS для хранения баз данных по сравнению с файлами веб-сайта

Вы можете найти решение намного быстрее, используя операции над множествами.

Сначала предположим, что у нас есть следующие зависимости:

deps = [(11, 2), (11, 9), (8, 9), (11, 10), (3, 10),
        (5, 11), (7, 11), (7, 8), (3, 8)]

, который формирует следующий график:

wikipedia dag [117]

чтобы найти курсы, которые ей нужно пройти в течение первого семестра:

semesters = []
sources = {start for start, end in deps}
sinks   = {end for start, end in deps}
semester = sources - sinks
semesters.append(semester)

т.е. найти все корни в графе (узлы без входящих стрелок).

Затем удалите корни:

deps = [(start, end) for start, end in deps if start not in semester]

и повторите ...

semesters = []
while deps:
    sources = {start for start, end in deps}
    sinks   = {end for start, end in deps}
    semester = sources - sinks
    semesters.append(semester)
    deps = [(start, end) for start, end in deps if start not in semester]

print("semesters needed:", 1 + len(semesters))

нам нужно добавить 1, так как при последнем удалении корней удаляются 2 уровня узлов.

Мы можем сравнить две версии, используя модуль timeit (я поместил ваш код в функцию и исправил несколько ошибок):

def semestercount():
    deps = [(11, 2), (11, 9), (8, 9), (11, 10), (3, 10),
            (5, 11), (7, 11), (7, 8), (3, 8)]
    count = 0
    while deps:
        sources = {start for start, end in deps}
        sinks   = {end for start, end in deps}
        semester = sources - sinks
        count += 1
        deps = [(start, end) for start, end in deps if start not in semester]
    return count + 1


def op_code():
    NM = [(11, 2), (11, 9), (8, 9), (11, 10), (3, 10),
          (5, 11), (7, 11), (7, 8), (3, 8)]
    nodes = list(set(sum(NM, ())))
    N = len(nodes)
    M = len(NM)
    remCourses = []
    courseRes = {}
    for i in range(N):
        courseRes[nodes[i]] = list()
        remCourses.append(nodes[i])

    for i in range(0,M):
        res = NM[i]
        courseRes[res[0]].append(res[1])

    semCount = 0
    while len(remCourses) > 0:
        newCourses = []
        for key in courseRes:
            if len(courseRes[key]) == 0:
                newCourses.append(key)


        for l in range(N):
            for course in newCourses:
                if course in courseRes[nodes[l]]:
                    courseRes[nodes[l]].remove(course)

        for course in newCourses:
            if course in remCourses:
                remCourses.remove(course)

        semCount += 1
    return semCount


import timeit
print timeit.timeit("semestercount()", "from __main__ import semestercount")
print timeit.timeit("op_code()", "from __main__ import op_code")

на моем компьютере он печатает: [1119 ]

5.85758427398
42.8849096743

так немного быстрее: -)

12
задан Jonik 19 May 2010 в 18:04
поделиться

4 ответа

When you say your web application files, I'm not sure what exactly you are referring to.

If you are referring to your deployed code, it probably doesn't make sense to use EBS. What you want to do is create an AMI with your prerequisites, then have a script to create an instance of that AMI and deploy your latest code. I highly recommend you automate and test this process as it's easy to forget about some setting you have to manually change somewhere.

If you are storing data files, that are modified by the running application, EBS may make sense. If this is something like user-uploaded images or similar, you will likely find that S3 gives you a much simpler model.

EBS would be good for: databases, lucene indexes, file based CMS, SVN repository, or anything similar to that.

7
ответ дан 2 December 2019 в 21:45
поделиться

EBS дает Вам персистентное устройство хранения данных поэтому, если Вы, экземпляр EC2 приводит файлы к сбою все еще, существуете. По-видимому, их увеличен производительность IO, но я протестировал бы ее, чтобы быть уверенным.

2
ответ дан 2 December 2019 в 21:45
поделиться

If your files are going to change frequently (like a DB does) and you don't want to keep syncing them to S3 (or somewhere else), then an EBS is a good way to go. If you make infrequent changes and you can manually (or scripted) sync the files as necessary then store them in S3. If you need to shutdown or you lose your instance for whatever reason, you can just pull them down when you start up the new instance. This is also assuming that you care about cost. If cost is not an issue, using the EBS is less complicated. I'm not sure if you plan on having a separate EBS for your DB and your web files but if you only plan on having one EBS and you have enough empty space on it for your web files, then again, the EBS is less complicated. If it's performance you are worried about, as mentioned, it's best to test your particular app.

2
ответ дан 2 December 2019 в 21:45
поделиться

Наш подход состоит в том, чтобы предварительно развернуть сценарий на нашем AMI, который извлекает самую последнюю и лучшую версию кода из системы контроля версий. Это упрощает быстрый запуск новых экземпляров или обновление всех запущенных экземпляров (мы выводим их из ротации балансировки нагрузки по одному, запускаем скрипт и возвращаем их обратно в ротацию).

UPDATE:

Если читать между строк, создается впечатление, что вы подключаете отдельный том EBS к экземпляру, поддерживаемому хранилищем экземпляров. AWS недавно представила инстансы с поддержкой EBS, которые имеют массу преимуществ по сравнению со старыми инстансами с хранилищем. Я по-прежнему монтирую свои данные MySQL в отдельный раздел EBS, чтобы при необходимости легко смонтировать их на другой сервер.

Я настоятельно рекомендую использовать экземпляр с поддержкой EBS с отдельным томом EBS для данных MySQL.

1
ответ дан 2 December 2019 в 21:45
поделиться
Другие вопросы по тегам:

Похожие вопросы: