Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions python/pyspark/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,12 +289,31 @@ def stop(self):

def parallelize(self, c, numSlices=None):
"""
Distribute a local Python collection to form an RDD.

>>> sc.parallelize(range(5), 5).glom().collect()
[[0], [1], [2], [3], [4]]
"""
numSlices = numSlices or self.defaultParallelism
Distribute a local Python collection to form an RDD. Use xrange if
the input represents a range for performance.

>>> sc.parallelize([0, 2, 3, 4, 6], 5).glom().collect()
[[0], [2], [3], [4], [6]]
>>> sc.parallelize(xrange(0, 6, 2), 5).glom().collect()
[[], [0], [], [2], [4]]
"""
numSlices = int(numSlices) if numSlices is not None else self.defaultParallelism
if isinstance(c, xrange):
size = len(c)
if size == 0:
return self.parallelize([], numSlices)
step = c[1] - c[0] if size > 1 else 1
c1 = xrange(c[0], c[0] + (size + 1) * step, step)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about pre-calculate all the boundaries for all the partitions?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only serializes an xrange object. If we pre-calculate the boundaries, the cost is O(p).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but the size + 1 is tricky, how about this one:

start = c[0]
def getStart(split):
      return start + size * split / numSlices * step
def f(split, iterator):
      return xrange(getStart(split), getStart(split+1), step)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is better!

def getStartIndex(split):
return split * size / numSlices

def f(split, iterator):
startIndex = getStartIndex(split)
endIndex = getStartIndex(split + 1)
return xrange(c1[startIndex], c1[endIndex], step)

return self.parallelize([], numSlices).mapPartitionsWithIndex(f)
# Calling the Java parallelize() method with an ArrayList is too slow,
# because it sends O(n) Py4J commands. As an alternative, serialized
# objects are written to a file and loaded through textFile().
Expand Down