我是python中的线程新手(实际上是python的新手)。 我编写了一些排序函数来测试python,并认为并行运行所有三种排序算法进行实时比较是个好主意。 但是,当我按顺序运行排序函数时,程序所需的时间比线程所有三种算法的时间要少。为什么会这样?线程是不是意味着不能像这些一样快速加速?
import random
import time
import copy
import BubbleSort
import SelectionSort
import InsertionSort
import threading
# MAX contains the amount of numbers to sort
from MAX import MAX
def generateRandomList(List):
"""
Generates a Random Usorted List
"""
for i in range(MAX + 1):
List.append(random.randrange(0, MAX + 1))
def displayList(List):
"""
Displays a List until the first hundred values
"""
for i in range(100):
print List[i]
def isSorted(List):
"""
Check if a List is sorted
"""
for i in range(MAX):
if List[i] > List[i + 1]:
return False
return True
def callSort(SortFunction, SortName):
"""
Calls the function and records its execution time
"""
StartTime = time.time()
CopyList = copy.deepcopy(List)
SortFunction(CopyList)
Sorted = isSorted(CopyList)
print ("%s Sort: %s seconds" % (SortName, time.time() - StartTime))
print "IsSorted: ", Sorted
print
class ThreadedSort(threading.Thread):
"""
Class for running Sorting algorithms in a threaded fashion
"""
def __init__(self, SortFunction, SortName):
threading.Thread.__init__(self)
self.SortFunction = SortFunction
self.SortName = SortName
def run(self):
callSort(self.SortFunction, self.SortName)
# Get the list
List = []
generateRandomList(List)
# Store sorting algorithms for easier access
SortFunctions = {
"Bubble" : BubbleSort.bubbleSort,
"Selection" : SelectionSort.selectionSort,
"Insertion" : InsertionSort.insertionSort
}
# Store threads in a list
SortingList = []
""" Begin Sorting """
# Threaded Sorting
for SortType in SortFunctions:
Sorting = threading.Thread(target = callSort, args = (SortFunctions[SortType], SortType))
SortingList.append(Sorting)
Sorting.start()
print "Threaded sorting has Begun..."
print
for Item in SortingList:
print Item
print
"""
# Sequential
print "Sequential sorting has Begun..."
print
for SortType in SortFunctions:
callSort(SortFunctions[SortType], SortType)
"""
""" End - Sorting """
这是我的代码。请帮助:)