使用Python編寫一個(gè)模仿CPU工作的程序
今天早上早些時(shí)候,在我的Planet Python源中,我讀到了一篇有趣的文章"開發(fā)CARDIAC:紙板計(jì)算機(jī)(Developing upwards: CARDIAC: The Cardboard Computer)",它是關(guān)于名為Cardiac的紙板計(jì)算機(jī)的.我的一些追隨者和讀者應(yīng)該知道,我有一個(gè)名為簡(jiǎn)單CPU(simple-cpu)的項(xiàng)目,過去的數(shù)月我一直工作于此,并且已經(jīng)發(fā)布了源代碼.我真的應(yīng)該給這個(gè)項(xiàng)目提供一個(gè)合適的許可證,這樣,其他人可能更感興趣,并在他們自己的項(xiàng)目中使用.不管怎樣,但愿在這發(fā)布之后,我可以完成這件事.
在讀完了這篇文章以及它鏈接的頁面后,我受到了一些啟發(fā),決定為它編寫我自己的模擬器,因?yàn)槲矣芯帉懽止?jié)碼引擎的經(jīng)驗(yàn).我計(jì)劃著跟隨這篇文章繼續(xù)往前,先寫一篇關(guān)于匯編器的文章,接下來是關(guān)于編譯器的文章.這樣,通過這些文章,你基本上可以學(xué)到,如何用Python為Cardiac創(chuàng)建編譯工具集. 在簡(jiǎn)單CPU(simple-cpu)項(xiàng)目中,我已經(jīng)編寫了一個(gè)完整的可工作的匯編器.在內(nèi)置的游戲中,已經(jīng)有了可工作的編譯器的最初步驟.我也選擇Cardiac作為一個(gè)驗(yàn)證機(jī)器是因?yàn)樗^對(duì)的簡(jiǎn)單.不需要復(fù)雜的記憶,每個(gè)操作碼只接受單一的參數(shù),所以它是絕好的學(xué)習(xí)工具.此外,所有的數(shù)據(jù)參數(shù)都是相同的,不需要檢測(cè)程序是需要一個(gè)寄存器,字符串或者還是內(nèi)存地址.實(shí)際上,只有一個(gè)寄存器,累加器.因此,讓我們開始吧!我們將基于類來創(chuàng)建,這樣包含范圍.如果你想嘗試的話,你可以簡(jiǎn)單通過子類來增加新的操作碼.首先,我們將集中于初始化例程.這個(gè)CPU非常簡(jiǎn)單,所以我們只需要初始化下面的內(nèi)容: CPU寄存器, 操作碼, 內(nèi)存空間, 讀卡器/輸入, 和 打印/tty/輸出.
class Cardiac(object):
""" This class is the cardiac "CPU". """
def __init__(self):
self.init_cpu()
self.reset()
self.init_mem()
self.init_reader()
self.init_output()
def reset(self):
""" This method resets the CPU's registers to their defaults. """
self.pc = 0 #: Program Counter
self.ir = 0 #: Instruction Register
self.acc = 0 #: Accumulator
self.running = False #: Are we running?
def init_cpu(self):
""" This fancy method will automatically build a list of our opcodes into a hash. This enables us to build a typical case/select system in Python and also keeps things more DRY. We could have also used the getattr during the process() method before, and wrapped it around a try/except block, but that looks a bit messy. This keeps things clean and simple with a nice one-to-one call-map. """
self.__opcodes = {}
classes = [self.__class__] #: This holds all the classes and base classes.
while classes:
cls = classes.pop() # Pop the classes stack and being
if cls.__bases__: # Does this class have any base classes?
classes = classes + list(cls.__bases__)
for name in dir(cls): # Lets iterate through the names.
if name[:7] == 'opcode_': # We only want opcodes here.
try:
opcode = int(name[7:])
except ValueError:
raise NameError('Opcodes must be numeric, invalid opcode: %s' % name[7:])
self.__opcodes.update({opcode:getattr(self, 'opcode_%s' % opcode)})
def init_mem(self):
""" This method resets the Cardiac's memory space to all blank strings, as per Cardiac specs. """
self.mem = ['' for i in range(0,100)]
self.mem[0] = '001' #: The Cardiac bootstrap operation.
def init_reader(self):
""" This method initializes the input reader. """
self.reader = [] #: This variable can be accessed after initializing the class to provide input data.
def init_output(self):
""" This method initializes the output deck/paper/printer/teletype/etc... """
self.output = []
但愿我寫的注釋能讓你們看明白代碼的各部分功能. 也許你已經(jīng)發(fā)現(xiàn)這段代碼處理指令集的方法(method)跟 simple-cpu 項(xiàng)目有所不同. 由于它能讓開發(fā)者根據(jù)自己的需求輕松的擴(kuò)展類庫, 我打算在后續(xù)的項(xiàng)目中繼續(xù)使用這種處理方式. 隨著我對(duì)各部分功能原理的深入理解, 項(xiàng)目也在不斷的發(fā)展變化. 其實(shí)吧, 做這樣一個(gè)項(xiàng)目真的能讓人學(xué)到不少東西. 對(duì)于精通計(jì)算機(jī)的人來說 , CPU 的工作原理啦, 指令集是怎么處理的啦, 都不是問題啦 . 關(guān)鍵是, 能夠按照自己的想法去實(shí)現(xiàn)這樣一個(gè) CPU 仿真器, 真的很好玩. 根據(jù)自己想象中的樣子, 親手打造出這樣一臺(tái)仿真器, 然后看著它屁顛屁顛的運(yùn)行著, 那叫一個(gè)有成就感.
接下來, 我們講下工具函數(shù)(utility functions), 這些函數(shù)在很多地方都會(huì)用到, 而且允許在子類(subclasses)中重寫:
def read_deck(self, fname):
""" 將指令讀到 reader 中. """
self.reader = [s.rstrip('\n') for s in open(fname, 'r').readlines()]
self.reader.reverse()
def fetch(self):
""" 根據(jù)指令指針(program pointer) 從內(nèi)存中讀出指令, 然后將指令指針加1. """
self.ir = int(self.mem[self.pc])
self.pc +=1
def get_memint(self, data):
""" 由于我們是以字符串形式(*string* based)保存內(nèi)存數(shù)據(jù)的, 要仿真 Cardiac, 就要將字符串轉(zhuǎn)化成整數(shù). 如果是其他存儲(chǔ)形式的內(nèi)存, 如 mmap, 可以根據(jù)需要重寫本函數(shù). """
return int(self.mem[data])
def pad(self, data, length=3):
""" 本函數(shù)的功能是像 Cardiac 那樣, 在數(shù)字的前面補(bǔ)0. """
orig = int(data)
padding = '0'*length
data = '%s%s' % (padding, abs(data))
if orig < 0:
return '-'+data[-length:]
return data[-length:]
本文后面我會(huì)另外給大家一段能結(jié)合 Mixin classes 使用的代碼, 靈活性(pluggable)更強(qiáng)些. 最后就剩下這個(gè)處理指令集的方法了:
def process(self):
""" 本函數(shù)只處理一條指令. 默認(rèn)情況下, 從循環(huán)代碼(running loop)中調(diào)用, 你也可以自己寫代碼, 以單步調(diào)試的方式調(diào)用它, 或者使用 time.sleep() 降低執(zhí)行的速度. 如果想用 TK/GTK/Qt/curses 做的前端界面(frontend), 在另外一個(gè)線程中操作, 也可以調(diào)用本函數(shù). """
self.fetch()
opcode, data = int(math.floor(self.ir / 100)), self.ir % 100
self.__opcodes[opcode](data)
def opcode_0(self, data):
""" 輸入指令 """
self.mem[data] = self.reader.pop()
def opcode_1(self, data):
""" 清除指令 """
self.acc = self.get_memint(data)
def opcode_2(self, data):
""" 加法指令 """
self.acc += self.get_memint(data)
def opcode_3(self, data):
""" 測(cè)試?yán)奂悠鲀?nèi)容指令 """
if self.acc < 0:
self.pc = data
def opcode_4(self, data):
""" 位移指令 """
x,y = int(math.floor(data / 10)), int(data % 10)
for i in range(0,x):
self.acc = (self.acc * 10) % 10000
for i in range(0,y):
self.acc = int(math.floor(self.acc / 10))
def opcode_5(self, data):
""" 輸出指令 """
self.output.append(self.mem[data])
def opcode_6(self, data):
""" 存儲(chǔ)指令 """
self.mem[data] = self.pad(self.acc)
def opcode_7(self, data):
""" 減法指令 """
self.acc -= self.get_memint(data)
def opcode_8(self, data):
""" 無條件跳轉(zhuǎn)指令 """
self.pc = data
def opcode_9(self, data):
""" 終止, 復(fù)位指令 """
self.reset()
def run(self, pc=None):
""" 這段代碼一直執(zhí)行到遇到 終止/復(fù)位 指令為止. """
if pc:
self.pc = pc
self.running = True
while self.running:
self.process()
print "Output:\n%s" % '\n'.join(self.output)
self.init_output()if __name__ == '__main__':
c = Cardiac()
c.read_deck('deck1.txt')
try:
c.run()
except:
print "IR: %s\nPC: %s\nOutput: %s\n" % (c.ir, c.pc, '\n'.join(c.output))
raise
這段是上面提到的, 能在 Mixin 中使用的代碼, 我重構(gòu)過后, 代碼如下 :
class Memory(object):
""" 本類實(shí)現(xiàn)仿真器的虛擬內(nèi)存空間的各種功能 """
def init_mem(self):
""" 用空白字符串清除 Cardiac 系統(tǒng)內(nèi)存中的所有數(shù)據(jù) """
self.mem = ['' for i in range(0,100)]
self.mem[0] = '001' #: 啟動(dòng) Cardiac 系統(tǒng).
def get_memint(self, data):
""" 由于我們是以字符串形式(*string* based)保存內(nèi)存數(shù)據(jù)的, 要仿真 Cardiac, 就要將字符串轉(zhuǎn)化成整數(shù). 如果是其他存儲(chǔ)形式的內(nèi)存, 如 mmap, 可以根據(jù)需要重寫本函數(shù). """
return int(self.mem[data])
def pad(self, data, length=3):
""" 在數(shù)字前面補(bǔ)0 """
orig = int(data)
padding = '0'*length
data = '%s%s' % (padding, abs(data))
if orig < 0:
return '-'+data[-length:]
return data[-length:]
class IO(object):
""" 本類實(shí)現(xiàn)仿真器的 I/O 功能. To enable alternate methods of input and output, swap this. """
def init_reader(self):
""" 初始化 reader. """
self.reader = [] #: 此變量在類初始化后, 可以用來讀取輸入的數(shù)據(jù).
def init_output(self):
""" 初始化諸如: deck/paper/printer/teletype/ 之類的輸出功能... """
self.output = []
def read_deck(self, fname):
""" 將指令讀到 reader 中. """
self.reader = [s.rstrip('\n') for s in open(fname, 'r').readlines()]
self.reader.reverse()
def format_output(self):
""" 格式化虛擬 I/O 設(shè)備的輸出(output) """
return '\n'.join(self.output)
def get_input(self):
""" 獲取 IO 的輸入(input), 也就是說用 reader 讀取數(shù)據(jù), 代替原來的 raw_input() . """
try:
return self.reader.pop()
except IndexError:
# 如果 reader 遇到文件結(jié)束標(biāo)志(EOF) 就用 raw_input() 代替 reader.
return raw_input('INP: ')[:3]
def stdout(self, data):
self.output.append(data)
class CPU(object):
""" 本類模擬 cardiac CPU. """
def __init__(self):
self.init_cpu()
self.reset()
try:
self.init_mem()
except AttributeError:
raise NotImplementedError('You need to Mixin a memory-enabled class.')
try:
self.init_reader()
self.init_output()
except AttributeError:
raise NotImplementedError('You need to Mixin a IO-enabled class.')
def reset(self):
""" 用默認(rèn)值重置 CPU 的寄存器 """
self.pc = 0 #: 指令指針
self.ir = 0 #: 指令寄存器
self.acc = 0 #: 累加器
self.running = False #: 仿真器的運(yùn)行狀態(tài)?
def init_cpu(self):
""" 本函數(shù)自動(dòng)在哈希表中創(chuàng)建指令集. 這樣我們就可以使用 case/select 方式調(diào)用指令, 同時(shí)保持代碼簡(jiǎn)潔. 當(dāng)然, 在 process() 中使用 getattr 然后用 try/except 捕捉異常也是可以的, 但是代碼看起來就沒那么簡(jiǎn)潔了. """
self.__opcodes = {}
classes = [self.__class__] #: 獲取全部類, 包含基類.
while classes:
cls = classes.pop() # 把堆棧中的類彈出來
if cls.__bases__: # 判斷有沒有基類
classes = classes + list(cls.__bases__)
for name in dir(cls): # 遍歷名稱.
if name[:7] == 'opcode_': # 只需要把指令讀出來即可 try:
opcode = int(name[7:])
except ValueError:
raise NameError('Opcodes must be numeric, invalid opcode: %s' % name[7:])
self.__opcodes.update({opcode:getattr(self, 'opcode_%s' % opcode)})
def fetch(self):
""" 根據(jù)指令指針(program pointer) 從內(nèi)存中讀取指令, 然后指令指針加 1. """
self.ir = self.get_memint(self.pc)
self.pc +=1
def process(self):
""" 處理當(dāng)前指令, 只處理一條. 默認(rèn)情況下是在循環(huán)代碼中調(diào)用(running loop), 也可以自己寫代碼, 以單步調(diào)試方式調(diào)用, 或者利用 time.sleep() 降低執(zhí)行速度. 在 TK/GTK/Qt/curses 做的界面的線程中調(diào)用本函數(shù)也是可以的. """
self.fetch()
opcode, data = int(math.floor(self.ir / 100)), self.ir % 100
self.__opcodes[opcode](data)
def opcode_0(self, data):
""" 輸入指令 """
self.mem[data] = self.get_input()
def opcode_1(self, data):
""" 清除累加器指令 """
self.acc = self.get_memint(data)
def opcode_2(self, data):
""" 加法指令 """
self.acc += self.get_memint(data)
def opcode_3(self, data):
""" 測(cè)試?yán)奂悠鲀?nèi)容指令 """
if self.acc < 0:
self.pc = data
def opcode_4(self, data):
""" 位移指令 """
x,y = int(math.floor(data / 10)), int(data % 10)
for i in range(0,x):
self.acc = (self.acc * 10) % 10000
for i in range(0,y):
self.acc = int(math.floor(self.acc / 10))
def opcode_5(self, data):
""" 輸出指令 """
self.stdout(self.mem[data])
def opcode_6(self, data):
""" 存儲(chǔ)指令 """
self.mem[data] = self.pad(self.acc)
def opcode_7(self, data):
""" 減法指令 """
self.acc -= self.get_memint(data)
def opcode_8(self, data):
""" 無條件跳轉(zhuǎn)指令 """
self.pc = data
def opcode_9(self, data):
""" 停止/復(fù)位指令"""
self.reset()
def run(self, pc=None):
""" 這段代碼會(huì)一直運(yùn)行, 直到遇到 halt/reset 指令才停止. """
if pc:
self.pc = pc
self.running = True
while self.running:
self.process()
print "Output:\n%s" % self.format_output()
self.init_output()
class Cardiac(CPU, Memory, IO):
passif __name__ == '__main__':
c = Cardiac()
c.read_deck('deck1.txt')
try:
c.run()
except:
print "IR: %s\nPC: %s\nOutput: %s\n" % (c.ir, c.pc, c.format_output())
raise
大家可以從 Developing Upwards: CARDIAC: The Cardboard Computer 中找到本文使用的 deck1.txt .
希望本文能啟發(fā)大家, 怎么去設(shè)計(jì)基于類的模塊, 插拔性強(qiáng)(pluggable)的 Paython 代碼, 以及如何開發(fā) CPU 仿真器. 至于本文 CPU 用到的匯編編譯器(assembler) , 會(huì)在下一篇文章中教大家.
這段是上面提到的, 能在 Mixin 中使用的代碼, 我重構(gòu)過后, 代碼如下 :
class Memory(object):
""" 本類實(shí)現(xiàn)仿真器的虛擬內(nèi)存空間的各種功能 """
def init_mem(self):
""" 用空白字符串清除 Cardiac 系統(tǒng)內(nèi)存中的所有數(shù)據(jù) """
self.mem = ['' for i in range(0,100)]
self.mem[0] = '001' #: 啟動(dòng) Cardiac 系統(tǒng).
def get_memint(self, data):
""" 由于我們是以字符串形式(*string* based)保存內(nèi)存數(shù)據(jù)的, 要仿真 Cardiac, 就要將字符串轉(zhuǎn)化成整數(shù). 如果是其他存儲(chǔ)形式的內(nèi)存, 如 mmap, 可以根據(jù)需要重寫本函數(shù). """
return int(self.mem[data])
def pad(self, data, length=3):
""" 在數(shù)字前面補(bǔ)0 """
orig = int(data)
padding = '0'*length
data = '%s%s' % (padding, abs(data))
if orig < 0:
return '-'+data[-length:]
return data[-length:]
class IO(object):
""" 本類實(shí)現(xiàn)仿真器的 I/O 功能. To enable alternate methods of input and output, swap this. """
def init_reader(self):
""" 初始化 reader. """
self.reader = [] #: 此變量在類初始化后, 可以用來讀取輸入的數(shù)據(jù).
def init_output(self):
""" 初始化諸如: deck/paper/printer/teletype/ 之類的輸出功能... """
self.output = []
def read_deck(self, fname):
""" 將指令讀到 reader 中. """
self.reader = [s.rstrip('\n') for s in open(fname, 'r').readlines()]
self.reader.reverse()
def format_output(self):
""" 格式化虛擬 I/O 設(shè)備的輸出(output) """
return '\n'.join(self.output)
def get_input(self):
""" 獲取 IO 的輸入(input), 也就是說用 reader 讀取數(shù)據(jù), 代替原來的 raw_input() . """
try:
return self.reader.pop()
except IndexError:
# 如果 reader 遇到文件結(jié)束標(biāo)志(EOF) 就用 raw_input() 代替 reader.
return raw_input('INP: ')[:3]
def stdout(self, data):
self.output.append(data)
class CPU(object):
""" 本類模擬 cardiac CPU. """
def __init__(self):
self.init_cpu()
self.reset()
try:
self.init_mem()
except AttributeError:
raise NotImplementedError('You need to Mixin a memory-enabled class.')
try:
self.init_reader()
self.init_output()
except AttributeError:
raise NotImplementedError('You need to Mixin a IO-enabled class.')
def reset(self):
""" 用默認(rèn)值重置 CPU 的寄存器 """
self.pc = 0 #: 指令指針
self.ir = 0 #: 指令寄存器
self.acc = 0 #: 累加器
self.running = False #: 仿真器的運(yùn)行狀態(tài)?
def init_cpu(self):
""" 本函數(shù)自動(dòng)在哈希表中創(chuàng)建指令集. 這樣我們就可以使用 case/select 方式調(diào)用指令, 同時(shí)保持代碼簡(jiǎn)潔. 當(dāng)然, 在 process() 中使用 getattr 然后用 try/except 捕捉異常也是可以的, 但是代碼看起來就沒那么簡(jiǎn)潔了. """
self.__opcodes = {}
classes = [self.__class__] #: 獲取全部類, 包含基類.
while classes:
cls = classes.pop() # 把堆棧中的類彈出來
if cls.__bases__: # 判斷有沒有基類
classes = classes + list(cls.__bases__)
for name in dir(cls): # 遍歷名稱.
if name[:7] == 'opcode_': # 只需要把指令讀出來即可 try:
opcode = int(name[7:])
except ValueError:
raise NameError('Opcodes must be numeric, invalid opcode: %s' % name[7:])
self.__opcodes.update({opcode:getattr(self, 'opcode_%s' % opcode)})
def fetch(self):
""" 根據(jù)指令指針(program pointer) 從內(nèi)存中讀取指令, 然后指令指針加 1. """
self.ir = self.get_memint(self.pc)
self.pc +=1
def process(self):
""" 處理當(dāng)前指令, 只處理一條. 默認(rèn)情況下是在循環(huán)代碼中調(diào)用(running loop), 也可以自己寫代碼, 以單步調(diào)試方式調(diào)用, 或者利用 time.sleep() 降低執(zhí)行速度. 在 TK/GTK/Qt/curses 做的界面的線程中調(diào)用本函數(shù)也是可以的. """
self.fetch()
opcode, data = int(math.floor(self.ir / 100)), self.ir % 100
self.__opcodes[opcode](data)
def opcode_0(self, data):
""" 輸入指令 """
self.mem[data] = self.get_input()
def opcode_1(self, data):
""" 清除累加器指令 """
self.acc = self.get_memint(data)
def opcode_2(self, data):
""" 加法指令 """
self.acc += self.get_memint(data)
def opcode_3(self, data):
""" 測(cè)試?yán)奂悠鲀?nèi)容指令 """
if self.acc < 0:
self.pc = data
def opcode_4(self, data):
""" 位移指令 """
x,y = int(math.floor(data / 10)), int(data % 10)
for i in range(0,x):
self.acc = (self.acc * 10) % 10000
for i in range(0,y):
self.acc = int(math.floor(self.acc / 10))
def opcode_5(self, data):
""" 輸出指令 """
self.stdout(self.mem[data])
def opcode_6(self, data):
""" 存儲(chǔ)指令 """
self.mem[data] = self.pad(self.acc)
def opcode_7(self, data):
""" 減法指令 """
self.acc -= self.get_memint(data)
def opcode_8(self, data):
""" 無條件跳轉(zhuǎn)指令 """
self.pc = data
def opcode_9(self, data):
""" 停止/復(fù)位指令"""
self.reset()
def run(self, pc=None):
""" 這段代碼會(huì)一直運(yùn)行, 直到遇到 halt/reset 指令才停止. """
if pc:
self.pc = pc
self.running = True
while self.running:
self.process()
print "Output:\n%s" % self.format_output()
self.init_output()
class Cardiac(CPU, Memory, IO):
passif __name__ == '__main__':
c = Cardiac()
c.read_deck('deck1.txt')
try:
c.run()
except:
print "IR: %s\nPC: %s\nOutput: %s\n" % (c.ir, c.pc, c.format_output())
raise
大家可以從Developing Upwards: CARDIAC: The Cardboard Computer 中找到本文使用的 deck1.txt 的代碼, 我用的是 從 1 計(jì)數(shù)到 10 的那個(gè)例子 .
- Win7下Python與Tensorflow-CPU版開發(fā)環(huán)境的安裝與配置過程
- python和bash統(tǒng)計(jì)CPU利用率的方法
- python統(tǒng)計(jì)cpu利用率的方法
- python獲取當(dāng)前計(jì)算機(jī)cpu數(shù)量的方法
- 10種檢測(cè)Python程序運(yùn)行時(shí)間、CPU和內(nèi)存占用的方法
- 淺談Python對(duì)內(nèi)存的使用(深淺拷貝)
- python多進(jìn)程中的內(nèi)存復(fù)制(實(shí)例講解)
- Python內(nèi)存管理方式和垃圾回收算法解析
- Python進(jìn)程間通信之共享內(nèi)存詳解
- python監(jiān)控linux內(nèi)存并寫入mongodb(推薦)
- 談?wù)勅绾问謩?dòng)釋放Python的內(nèi)存
- Python深入06——python的內(nèi)存管理詳解
- Python獲取CPU、內(nèi)存使用率以及網(wǎng)絡(luò)使用狀態(tài)代碼
相關(guān)文章
Python中各類Excel表格批量合并問題的實(shí)現(xiàn)思路與案例
在日常工作中,可能會(huì)遇到各類表格合并的需求。本文主要介紹了Python中各類Excel表格批量合并問題的實(shí)現(xiàn)思路與案例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
python 網(wǎng)頁解析器掌握第三方 lxml 擴(kuò)展庫與 xpath 的使用方法
這篇文章主要介紹了python 網(wǎng)頁解析器掌握第三方 lxml 擴(kuò)展庫與 xpath 的使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

