Çözme embarassingly paralel sorunları Python kullanarak Çoklu işlem | Netgez.com
SORU
1 Mart 2010, PAZARTESÄ°


Çözme embarassingly paralel sorunları Python kullanarak Çoklu işlem

Nasıl bir multiprocessing embarrassingly parallel problems çözmek için kullanır?

Embarassingly paralel sorunları genellikle üç temel bölümden oluşur:

  1. Okuyungiriş verileri (dosya, veritabanı, tcp bağlantısı, vb.).
  2. Çalıştırınher bir hesaplama olduğu giriş verileri, hesaplamalarbaşka bir hesaplama bağımsız.
  3. Yazınhesaplamalar (dosya, veritabanı, tcp bağlantısı, vb.) sonuçları.

Ä°ki boyutlu program parallelize edebiliriz:

  • Bölüm 2 her hesaplama bağımsız olduÄŸundan birden fazla çekirdek üzerinde çalışabilir,; iÅŸlem sırası önemli deÄŸildir.
  • Her bölümü bağımsız olarak çalışabilir. Bölüm 1. veri giriÅŸ sırası, bölüm 2 Çek veri kapalı giriÅŸ sırası ve sonuçları üzerine bir çıkış sırası ve Bölüm 3 can çekin sonuçlar dışı çıkış sırası ve yazma onları.

Bu eşzamanlı programlamanın en temel bir desen gibi görünüyor, ama hala bunu çözmeye çalışırken kayboldumhadi bu nasıl yapılır Çoklu işlem kullanarak göstermek için kurallı bir örnek yazın.

Burada örnek problem:, toplamları hesaplamak girdi. gibi tamsayılar satır CSV file Verilen Buna paralel olarak çalıştırabilirsiniz her üç kısma da ayrı bir sorun:

  1. Ham veri giriş dosyası (listeler tamsayılar iterables/) süreci
  2. Buna paralel olarak verilerin toplamlarını hesaplamak
  3. Çıkış toplamları

Aşağıda bu üç görevleri çözer, tek süreci geleneksel bağlı Python programı:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# basicsums.py
"""A program that reads integer values from a CSV file and writes out their
sums to another CSV file.
"""

import csv
import optparse
import sys

def make_cli_parser():
    """Make the command line interface parser."""
    usage = "\n\n".join(["python %prog INPUT_CSV OUTPUT_CSV",
            __doc__,
            """
ARGUMENTS:
    INPUT_CSV: an input CSV file with rows of numbers
    OUTPUT_CSV: an output file that will contain the sums\
"""])
    cli_parser = optparse.OptionParser(usage)
    return cli_parser


def parse_input_csv(csvfile):
    """Parses the input CSV and yields tuples with the index of the row
    as the first element, and the integers of the row as the second
    element.

    The index is zero-index based.

    :Parameters:
    - `csvfile`: a `csv.reader` instance

    """
    for i, row in enumerate(csvfile):
        row = [int(entry) for entry in row]
        yield i, row


def sum_rows(rows):
    """Yields a tuple with the index of each input list of integers
    as the first element, and the sum of the list of integers as the
    second element.

    The index is zero-index based.

    :Parameters:
    - `rows`: an iterable of tuples, with the index of the original row
      as the first element, and a list of integers as the second element

    """
    for i, row in rows:
        yield i, sum(row)


def write_results(csvfile, results):
    """Writes a series of results to an outfile, where the first column
    is the index of the original row of data, and the second column is
    the result of the calculation.

    The index is zero-index based.

    :Parameters:
    - `csvfile`: a `csv.writer` instance to which to write results
    - `results`: an iterable of tuples, with the index (zero-based) of
      the original row as the first element, and the calculated result
      from that row as the second element

    """
    for result_row in results:
        csvfile.writerow(result_row)


def main(argv):
    cli_parser = make_cli_parser()
    opts, args = cli_parser.parse_args(argv)
    if len(args) != 2:
        cli_parser.error("Please provide an input file and output file.")
    infile = open(args[0])
    in_csvfile = csv.reader(infile)
    outfile = open(args[1], 'w')
    out_csvfile = csv.writer(outfile)
    # gets an iterable of rows that's not yet evaluated
    input_rows = parse_input_csv(in_csvfile)
    # sends the rows iterable to sum_rows() for results iterable, but
    # still not evaluated
    result_rows = sum_rows(input_rows)
    # finally evaluation takes place as a chain in write_results()
    write_results(out_csvfile, result_rows)
    infile.close()
    outfile.close()


if __name__ == '__main__':
    main(sys.argv[1:])

Bu program alalım ve üç parça yukarıda belirtilen parallelize için çoklu kullanmak için yeniden yazın. Aşağıda yorum parçaları Adres tamamlanmıştır gereken bu yeni, parallelized program iskeleti:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# multiproc_sums.py
"""A program that reads integer values from a CSV file and writes out their
sums to another CSV file, using multiple processes if desired.
"""

import csv
import multiprocessing
import optparse
import sys

NUM_PROCS = multiprocessing.cpu_count()

def make_cli_parser():
    """Make the command line interface parser."""
    usage = "\n\n".join(["python %prog INPUT_CSV OUTPUT_CSV",
            __doc__,
            """
ARGUMENTS:
    INPUT_CSV: an input CSV file with rows of numbers
    OUTPUT_CSV: an output file that will contain the sums\
"""])
    cli_parser = optparse.OptionParser(usage)
    cli_parser.add_option('-n', '--numprocs', type='int',
            default=NUM_PROCS,
            help="Number of processes to launch [DEFAULT: Þfault]")
    return cli_parser


def main(argv):
    cli_parser = make_cli_parser()
    opts, args = cli_parser.parse_args(argv)
    if len(args) != 2:
        cli_parser.error("Please provide an input file and output file.")
    infile = open(args[0])
    in_csvfile = csv.reader(infile)
    outfile = open(args[1], 'w')
    out_csvfile = csv.writer(outfile)

    # Parse the input file and add the parsed data to a queue for
    # processing, possibly chunking to decrease communication between
    # processes.

    # Process the parsed data as soon as any (chunks) appear on the
    # queue, using as many processes as allotted by the user
    # (opts.numprocs); place results on a queue for output.
    #
    # Terminate processes when the parser stops putting data in the
    # input queue.

    # Write the results to disk as soon as they appear on the output
    # queue.

    # Ensure all child processes have terminated.

    # Clean up files.
    infile.close()
    outfile.close()


if __name__ == '__main__':
    main(sys.argv[1:])

Bu kod parçaları, yanı sıra test amaçlı another piece of code that can generate example CSV files, found on github olabilir.

Uzmanları bu soruna yaklaşır mısınız eşzamanlılık nasıl herhangi bir fikir burada seviniriz.

< / ^ hr .

İşte bu sorun hakkında düşünmeye zaman geçirdim bazı sorular.Bonus/adresleme için tüm noktaları:

  • Veri okuma ve sıraya yerleÅŸtirirken, alt süreç olması gerekir, ya da ana iÅŸlem tüm giriÅŸ okumak kadar engelleme olmadan bunu yapabilir?
  • Aynı ÅŸekilde, sonuçları iÅŸlenmiÅŸ sıradan yazmak için bir çocuk süreç olması gerekir, ya da ana iÅŸlem tüm sonuçlar için beklemek zorunda kalmadan bunu yapabilirsiniz?
  • Sum iÅŸlemleri için processes pool Bir kullanmalıyım?
    • Evet, ne yöntemi, sonuçları giriÅŸ ve çıkış iÅŸlemleri engellemeden giriÅŸ kuyruÄŸuna geldiÄŸin de iÅŸleme baÅŸlamak için almak için havuza diyebilir miyim? apply_async()? map_async()? imap()? imap_unordered()?
  • UlaÅŸtırmamız gerek yoktu sifon giriÅŸ ve çıkış sırası olarak veri girilen onları, ama bekleyebilirim kadar tüm giriÅŸ oldu ayrıştırılır ve tüm sonuçlar hesaplanmıştır (örneÄŸin, çünkü bildiÄŸimiz tüm giriÅŸ ve çıkış uygun sistem belleÄŸi). Herhangi bir ÅŸekilde algoritma (örneÄŸin, herhangi bir çalışan aynı anda I/O) deÄŸiÅŸtirmek gerekir?

CEVAP
2 Mart 2010, Salı


Benim çözüm ve çıkış sırası giriş sırası olarak aynı olduğundan emin olmak için ekstra bell bir düdük var. Çoklu kullanıyorum.sıranın işlemler arasında veri göndermek için, her işlem sıraları kontrol bırakmaya bilir dur iletileri gönderme. Kaynak yorum ama neler olduğunu açıkça değilse bana bildirin gerektiğini düşünüyorum.

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# multiproc_sums.py
"""A program that reads integer values from a CSV file and writes out their
sums to another CSV file, using multiple processes if desired.
"""

import csv
import multiprocessing
import optparse
import sys

NUM_PROCS = multiprocessing.cpu_count()

def make_cli_parser():
    """Make the command line interface parser."""
    usage = "\n\n".join(["python %prog INPUT_CSV OUTPUT_CSV",
            __doc__,
            """
ARGUMENTS:
    INPUT_CSV: an input CSV file with rows of numbers
    OUTPUT_CSV: an output file that will contain the sums\
"""])
    cli_parser = optparse.OptionParser(usage)
    cli_parser.add_option('-n', '--numprocs', type='int',
            default=NUM_PROCS,
            help="Number of processes to launch [DEFAULT: Þfault]")
    return cli_parser

class CSVWorker(object):
    def __init__(self, numprocs, infile, outfile):
        self.numprocs = numprocs
        self.infile = open(infile)
        self.outfile = outfile
        self.in_csvfile = csv.reader(self.infile)
        self.inq = multiprocessing.Queue()
        self.outq = multiprocessing.Queue()

        self.pin = multiprocessing.Process(target=self.parse_input_csv, args=())
        self.pout = multiprocessing.Process(target=self.write_output_csv, args=())
        self.ps = [ multiprocessing.Process(target=self.sum_row, args=())
                        for i in range(self.numprocs)]

        self.pin.start()
        self.pout.start()
        for p in self.ps:
            p.start()

        self.pin.join()
        i = 0
        for p in self.ps:
            p.join()
            print "Done", i
            i  = 1

        self.pout.join()
        self.infile.close()

    def parse_input_csv(self):
            """Parses the input CSV and yields tuples with the index of the row
            as the first element, and the integers of the row as the second
            element.

            The index is zero-index based.

            The data is then sent over inqueue for the workers to do their
            thing.  At the end the input process sends a 'STOP' message for each
            worker.
            """
            for i, row in enumerate(self.in_csvfile):
                row = [ int(entry) for entry in row ]
                self.inq.put( (i, row) )

            for i in range(self.numprocs):
                self.inq.put("STOP")

    def sum_row(self):
        """
        Workers. Consume inq and produce answers on outq
        """
        tot = 0
        for i, row in iter(self.inq.get, "STOP"):
                self.outq.put( (i, sum(row)) )
        self.outq.put("STOP")

    def write_output_csv(self):
        """
        Open outgoing csv file then start reading outq for answers
        Since I chose to make sure output was synchronized to the input there
        is some extra goodies to do that.

        Obviously your input has the original row number so this is not
        required.
        """
        cur = 0
        stop = 0
        buffer = {}
        # For some reason csv.writer works badly across processes so open/close
        # and use it all in the same process or else you'll have the last
        # several rows missing
        outfile = open(self.outfile, "w")
        self.out_csvfile = csv.writer(outfile)

        #Keep running until we see numprocs STOP messages
        for works in range(self.numprocs):
            for i, val in iter(self.outq.get, "STOP"):
                # verify rows are in order, if not save in buffer
                if i != cur:
                    buffer[i] = val
                else:
                    #if yes are write it out and make sure no waiting rows exist
                    self.out_csvfile.writerow( [i, val] )
                    cur  = 1
                    while cur in buffer:
                        self.out_csvfile.writerow([ cur, buffer[cur] ])
                        del buffer[cur]
                        cur  = 1

        outfile.close()

def main(argv):
    cli_parser = make_cli_parser()
    opts, args = cli_parser.parse_args(argv)
    if len(args) != 2:
        cli_parser.error("Please provide an input file and output file.")

    c = CSVWorker(opts.numprocs, args[0], args[1])

if __name__ == '__main__':
    main(sys.argv[1:])

Bunu PaylaÅŸ:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VÄ°DEO

Rastgele Yazarlar

  • Carlos Delgado

    Carlos Delga

    21 HAZÄ°RAN 2011
  • Howcast

    Howcast

    4 EKÄ°M 2007
  • Snazzy Labs

    Snazzy Labs

    9 Aralık 2008