Home

Relatório

image

Contents

1. This method initializes jButton return javax swing JButton Tu private JButton getJButton if jButton null jButton new JButton jButton setText OK jButton addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e System out println warning ok generated Event stub actionPerformed TODO Auto WarningDialog this setVisible false return jButton This method initializes jTextPaneMessage return javax swing JTextPane xj private JTextPane getJTextPaneMessage if jTextPaneMessage null jTextPaneMessage new JTextPane jTextPaneMessage setEditable false jTextPaneMessage setBacRground new Color 240 240 240 return jTextPaneMessage 113 116
2. e printStackTrace System out println e throw new MemAccessFormatException Argumentos incompativeis Representa um acesso a mem ria param ma string com formato address type size m f public MemAccess String ma throws MemAccessFormatException try StringTokenizer ma_st new StringTokenizer ma this hex ma st nextToken this address hexToLong this hex this type ma_st nextToken charAt 0 this size strToInt ma st nextToken catch Exception e e printStackTrace System out println e throw new MemAccessFormatException String com formato errado Mamas 47 116 Arquitectura Avan ada de Computadores Simulador de Cache public MemAccess getCopy try return new MemAccess hex type size catch Exception e System out println e getMessage return null public void incAddress this address public String getHexAddress return this hex public String getAccessType return this type public boolean isInstructionAccess LE type EM type A return true else return false public boolean isDataReadAccess if type R type r return true else return false public boolean isDataWriteAccess if type W type w return true else return false public int getSize return this size public long getAddress return this address C
3. public int getSetIndex MemAccess ma return uCache getSetIndex ma retorna o index do bloco ao qual pertence o primeiro set public int getSetBlockIndex MemAccess ma return uCache getSetIndex ma uCache getAssociatividade public void doMemAccess MemAccess ma throws Cache CacheFormatException this lastMemAccess ma getCopy uCache doMemAccess ma public static void main String args try if args length 6 System out println Wrong usage try System out println java cacheSim SplitCache n t lt cache size KB gt n t lt block size bytes gt n t lt associativity gt n t lt LRU FIFO RANDOM gt n t lt WR_BACK WR THROUGH MnNt trace file System exit 0 int size Integer parseInt args 0 int block Integer parseInt args 1 int assoc Integer parseInt args 2 int sub 1 int wr 1 if args 3 compareTo LRU 0 sub Cache S LRU if args 3 compareTo FIFO 0 sub Cache S FIFO if args 3 compareTo RANDOM 0 sub Cache S RANDOM if args 4 compareTo WR BACK 0 wr Cache WR BACK ALLOCATE if args 4 compareTo WR THROUGH 0 wr Cache WR THROUGH NO ALLOCATE Cache cache new Cache size block assoc sub wr false UnifiedCache uCache new UnifiedCache cache MemAccessFile maf new MemAccessFile args 5 int i for i 0 maf hasMore i MemAccess ma maf getNext System o
4. package cacheSim import java awt Canvas import java awt Color import java awt Graphics Esta classe representa a parte de Desenho da interface gr fica Tem os dados da simula o como a cache aonde vai buscar a informa o para representa la no ecra author Manuel public class MainCanvas extends Canvas public static final long serialVersionUID 0 public int my x public int my y public static final int X IND BLOCK 70 coordenadas iniciais dos v rios elementos possivel implementa o do zoom private float factor 1 private MyPoint cl new MyPoint 15 65 cachel private MyPoint c2 new MyPoint 15 0 cache 2 private final MyPoint bb new MyPoint 5 15 tamanho minimo para um byte de um bloco o quadrado mais pequeno private MyPoint bsizel new MyPoint 0 0 private MyPoint bsize2 new MyPoint 0 0 blocR seleccionado private boolean isBlockSelected private MyPoint blockSelected private MyPoint blockSelectedSize private int cacheSelected 0 private int selected set index private SimParams sim null public MainCanvas super 1 this setSize 1024 1024 this setBackground Color white my x 10 my y 10 this isBlockSelected false public MyPoint getBlockByteDrawSize return bb public MyPoint getCachelPos return cl public MyPoint getCache2Pos return c2 38 116 Arquitectura Av
5. this setSize 450 350 this setLocationRelativeTo null this setResizable false mainFrame frame This method initializes this return void x private void initialize this setPreferredSize new Dimension 400 400 this setContentPane getJContentPane This method initializes jContentPane Qreturn javax swing JPanel private JPanel getJContentPane if jContentPane null jContentPane new JPanel jContentPane setLayout new BorderLayout jContentPane add getJPanelCenter java awt BorderLayout CENTER jContentPane setBorder BorderFactory createEmptyBorder 10 10 10 10 return jContentPane This method initializes jPanelCenter 104 116 Arquitectura Avan ada de Computadores Simulador de Cache return javax swing JPanel private JPanel getJPanelCenter if jPanelCenter null jPanelCenter new JPanel new BorderLayout jPanelCenter add getJPanel BorderLayout NORTH jPanelCenter add getJPanell BorderLayout CENTER jPanelCenter add getJPanell2 java awt BorderLayout SOUTH return jPanelCenter This method initializes jPanel return javax swing JPanel 7 private JPanel getJPanel if jPanel null jLabel new JLabel jLabel setText Trace File jPanel new JPanel new FlowLayout FlowLayout LEFT jPanel add jLabel null jPanel add getJTextFieldTrace
6. da lhe um espa o extra pra separar as caches blocks d cache getNumBlocks block size d cache getBlockSize bsize2 x bb x block size bsize2 y bb y g setColor Color BLACK g fillRect 0 c2 y 32 120 15 g setColor Color WHITE g drawString Data cache c2 x c2 y 20 g setColor Color LIGHT GRAY g drawString tag eE ez my 62 73 g setColor Color LIGHT GRAY g drawString block c2 x X IND BLOCK 35 for int i 0 i blocks i if d cache getBlock i isClean g setColor Color GREEN g drawString empty c2 x c2 y bb y Jelsel g setColor Color BLACR 40 116 Arquitectura Avan ada de Computadores Simulador de Cache g drawString d cache getBlock i getTag c2 x c2 y bb y bb y i 3 g setColor new Color 222 240 255 g fillRect c2 x X_IND_BLOCK c2 y bb y i bsize2 x bb y g setColor Color GRAY g drawRect c2 x X_IND_BLOCK c2 y bb y i bsize2 x bb y Tf print dirty bit status if d cache getBlock i isDirty g setColor new Color 200 0 0 else g setColor Color LIGHT GRAY g fillRect c2 x X IND BLOCK 10 c2 y bb y i 10 bb y g setColor Color GRAY g drawRect c2 x X IND BLOCK 10 c2 y bb y i 10 bb y else desenho de uma cache unificada if sim isUnifiedCache RK KKK IK KKK IR IK KR IA IR IR IA I I I RR RR A px DESENHO CACHE UNIFICADA Pe RR KKK AR RR RR RR RR RR RR RR RR RR RR I
7. jLabel7 setText replace policy jPanel9 new JPanel jPanel9 setPreferredSize labelDim jPanel9 add jLabel7 null return jPanel9 This method initializes jComboBox return javax swing JComboBox A private JComboBox getJComboBoxReplacePolicy if jComboBoxReplacePolicy null jComboBoxReplacePolicy new JComboBox jComboBoxReplacePolicy addItem new MyItem LRU Cache S LRU 95 116 Arquitectura Avan ada de Computadores Simulador de Cache jComboBoxReplacePolicy addItem new MyItem Random Cache S RANDOM jComboBoxReplacePolicy addItem new MyItem Fifo Cache S FIFO return jComboBoxReplacePolicy This method initializes jPanellO return javax swing JPanel XI private JPanel getJPanell0 if jPanell10 null jPanell0 new JPanel new FlowLayout FlowLayout LEFT jPanell0 add getJPanelll null jPanell0 add getJComboBoxWritePolicy null return jPanell0 This method initializes jPanelll return javax swing JPanel private JPanel getJPanelll if jPanelll null jLabel8 new JLabel jLabel8 setText write policy jPanelll new JPanel jPanelll setPreferredSize labelDim jPanelll add jLabel8 null return jPanelll This method initializes jComboBoxl return javax swing JComboBox x private JComboBox getJComboBoxWritePolicy if jComboBoxWritePolicy null jC
8. private private private JPanel jPanel5 null JLabel jLabel3 null JTextField jTextFieldi null JLabel jLabel4 null JPanel jPanel6 null JPanel jPanel7 null JLabel jLabel5 null JTextField jTextField2 null JLabel jLabel6 null JPanel jPanel8 null JPanel jPanel9 null JLabel jLabel7 null JComboBox jComboBoxReplacePolicy null JPanel jPanellO null JPanel jPanelll null JLabel jLabel8 null JComboBox jComboBoxWritePolicy null JPanel jPanell4 null JPanel jPanell5 null JPanel jPanell6 null JLabel jLabel9 null JTextField jTextField3 null JLabel jLabellO null JPanel jPanell7 null JPanel jPanell8 null JLabel jLabelll null JTextField jTextField4 null JLabel jLabell2 null JPanel jPanell9 null JPanel jPanel20 null JLabel jLabell3 null JTextField jTextField5 null JLabel jLabell4 null JPanel jPanel21 null JPanel jPanel22 null JLabel jLabell5 null JComboBox jComboBoxReplacePolicyICache JPanel jPanel23 null JPanel jPanel24 null null 89 116 Arquitectura Avan ada de Computadores Simulador de Cache private JLabel jLabell6 null private JComboBox jComboBoxWritePolicyICache null private JCheckBox jCheckBoxNextLevelReg null This is the default constructor public SplitCacheDialog RunProgram frame super frame true initialize this setTi
9. Universidade do Porto F F U Bg Faculdade de Engenharia Arquitectura Avancada de Computadores 2005 2006 RELAT RIO Simulador de Cache Dezembro de 2005 Autor Manuel Maia ei00128 fe up pt Docente da disciplina Jo o Canas Ferreira jcf fe up pt Arquitectura Avan ada de Computadores Simulador de Cache ndice 1 Introdu o gt a a a lt Gil 1 DS JDESCTI O cas cenario uses decada Dons cia eta seis 2 2 1 F ncionalidades T 2 2 2 ATQUILSCLUL A ie eet tere a t re ESSEN Phe E USA ea SEEN 1 SE Re gea 4 2 3 ATSOritmos i tat tt ec reU e DER RU eb o Gor ue 4 24 Detalhes de implementa o neniet nyere ioris 6 25 Testes e valida o ci imita eae mia ees 1 2 5 1 Goer ncia dos Is e TTT 1 2 5 2 Algoritmos de substitui o 00 ele eee eee eee nennen 8 2 5 3 Resultados do Te Te a Rte ptt e eene 9 3 CONCIUS ES ict ete ee E e ee ee wo the ele edi eee tiene reete oues 10 4 Melhoramentos e p e t e ae HE 11 5 Refer ncias saarn et TE en 12 5 1 Bibliografia ie pacto eis He ee atleta Masies 12 5 2 SOPLW ATC RR 12 6 Ap ndice liaise DOR d iro EE tein 13 6 1 Manual do utilizador iced ete He eR nat ei 13 6 1 Escolher a simula o nitat ti te aci 13 6 1 2 Especificar a Cache mi ede eget ei 14 6 1 3 Correra H EL erede hp e EE ER pes 15 6 1 4 Resultado de um acesso sessi enne nennen 16 6 1 5 Acessos ao pr ximo n vel de mem ria e
10. block size jPanel8 new JPanel jPanel8 add jLabel2 null jPanel8 setPreferredSize labelDim return jPanel8 This method initializes jPanel9 w return javax swing JPanel y private JPanel getJPanel9 if jPanel9 null jLabel7 new JLabel jLabel7 setText replace policy jPanel9 new JPanel jPanel9 add jLabel7 null jPanel9 setPreferredSize labelDim return jPanel9 This method initializes jPanellO return javax swing JPanel 108 116 Arquitectura Avan ada de Computadores Simulador de Cache private JPanel getJPanell0 if jPanell0 null jPanell0 new JPanel new FlowLayout FlowLayout LEFT jPanell0 add getJPanelll null jPanell0 add getJComboBoxWritePolicy null return jPanell0 This method initializes jPanelll return javax swing JPanel X private JPanel getJPanelll if jPanelll null jLabel8 new JLabel jLabel8 setText write policy jPanelll new JPanel jPanelll add jLabel8 null jPanelll setPreferredSize labelDim return jPanelll This method initializes jComboBox return javax swing JComboBox x4 private JComboBox getJComboBoxWritePolicy if jComboBoxWritePolicy null jComboBoxWritePolicy new JComboBox 1 jComboBoxWritePolicy addItem new MyItem write back write allocate Cache WR BACK ALLOCATE jComboBoxWritePolicy addItem new M
11. jScrollPane setBackground java awt SystemColor text jScrollPane setViewportView getJTextArea return jScrollPane 8jve decl index 0 visual constraint 10 10 21 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 2 Block Esta classe representa um bloco de cache tem v rias vari veis de estado como dirty empty tag etc Tem tamb m vari veis de suporte aos algoritmos de substitui o e escrita como a ultima vez que foi usado LRU ou quando foi criado FIFO Na situa o foi criado significa que existiu uma substitui o ou escrita enquanto que foi usado engloba as situa es anteriores e essa vari vel tamb m actualizada quando existe um hit package cacheSim Representa o bloco de uma cache Tem as variaveis sobre o estado do bloco dirty empty tag etc e vari veis de suporte aos algoritmos de substituig o e escrita author Manuel SL public class Block dirty bit se o bloco de cache foi alterado e n o foi propragado para mem ria public boolean dirty bit se o bloco est limpo ainda n foi usado public boolean clean public long tag private int block size representa o ultimo acesso feito que resultou num dirty state public MemAccess lastMemAccess public MemAccess lastDirtyMemAccess private long lastAccess variavel para a pol tica de susbstitui o LRU private long creationTime variavel
12. return javax swing JTextField ef private JTextField getJTextFieldAddress if jTextFieldAddress null jTextFieldAddress new JTextField jTextFieldAddress setColumns 10 jTextFieldAddress setEditable false jTextFieldAddress setBackground Color WHITE return jTextFieldAddress This method initializes jTextFieldAccessType Qreturn javax swing JTextField A private JTextField getJTextFieldAccessType if jTextFieldAccessType null jTextFieldAccessType new JTextField jTextFieldAccessType setColumns 5 jTextFieldAccessType setEditable false jTextFieldAccessType setBackground Color WHITE return jTextFieldAccessType This method initializes jTextFieldAccessSize 68 116 Arquitectura Avan ada de Computadores Simulador de Cache return javax swing JTextField private JTextField getJTextFieldAccessSize if jTextFieldAccessSize null jTextFieldAccessSize new JTextField jTextFieldAccessSize setColumns 3 jTextFieldAccessSize setEditable false jTextFieldAccessSize setBackground Color WHITE return jTextFieldAccessSize This method initializes jMenuItemNewSim2 return javax swing JMenuItem x private JMenuItem getJMenuItemNewSim2 if jMenuItemNewSim2 null jMenuItemNewSim2 new JMenuItem jMenuItemNewSim2 setText New SplitCache Simulation jMenuItemNewSim2 addActionListener new java awt event Action
13. 1 T public void removeBlockSelected this isBlockSelected false 46 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 6 MemAccess Representa um acesso a mem ria esta classe amplamente usada pelas restantes no programa Contem o endere o tamanho e tipo do acesso Tem as respectivas fun es para usar esta classe package cacheSim import java util StringTokenizer Representa um acesso a mem ria tem endere o de memoria tipo R N I e tamanho e algumas fun es utilitarias Gauthor Manuel SE P P RR GRO E public class MemAccess private long address endere o n mero sem sinal 32 bits em hexadecimal private char type tipo R leitura de dados W escrita de dados I acesso a instru o private int size tamanho n mero sem sinal indicando a dimens o do item transferido em bytes private String hex Representa um acesso a mem ria param address endere o de posi o de mem ria em hexadecimal 32 bits Gparam type tipo R leitura de dados W escrita de dados I acesso a instru o param size tamanho n mero sem sinal indicando a dimens o do item transferido F 0X X em bytes Y public MemAccess String address String type String size throws MemAccessFormatException try this address hexToLong address address this type type charAt 0 this size strToInt size this hex address catch Exception e
14. 3 c2 y bb y i bsize2 x X IND BLOCK 3 bb y Jelse if sim isUnifiedCache int i sim getUnifiedCache getLastAccessBlockIndex pk se trata do index nao pode ser inserido c digo aqui porque ainda nada foi inicializado i 1 if i gt 0 MemAccess lma sim getUnifiedCache getLastMemAccess int offset int size lma getSize offset int sim getUnifiedCache getUCache getOffset Ima cache de instru es g setColor Color ORANGE g fillRect cl x X IND BLOCK 1 cl y bb y i bsizel x 1 bb y for int j 0 j lt size j g setColor Color RED g fillRect cl x X IND BLOCK offset bb x j bb x cl y bb y i bb x bb y g setColor Color BLACK g drawRect cl x X IND BLOCK offset bb x j bb x cl y bb y i bb x bb y T g setColor Color BLACR g drawRect cl x 3 cl y bb y i bsizel x X IND BLOCK 3 bb y 45 116 Arquitectura Avan ada de Computadores Simulador de Cache end sim null para teste imprime uma barra em cima de tudo g fillRect 0 0 my x my y public void setBlockSelected int x this selected set index set index this blockSelected new MyPoint x y this isBlockSelected true if block lt 0 this blockSelectedSize this cacheSelected 0 int y int block int set index bsizel else T his blockSelectedSize bsize2 his cacheSelected
15. XL System out println Vai para o set set n_sets this sets System out println Access n accesst NInstrAccess n_instr_access NHits n hitst NMisses n missest Falhas milhar de instr n misses 1000 n access public void printStatistcs System out println in Cache Info System out println Size this size 1024 kB System out println Block Size this block size bytes System out println Associatividade this associatividade Policy this replacePolicyToString if this falhas compulsorias System out println in Cache Statistics with start misses else System out printin n Cache Statistics without start misses System out println Access n access System out println NInstrAccess tn instr access System out println NDataReadAccess this n dataread access System out println NDataWriteAccess this n datawrite access System out println NWriteBacks this n write backs System out println NWriteThroughs this n write throughs System out println NAccessToNextLevel this n access to next level System out println NHits n hits System out println NMisses tn misses System out println Misses n misses 1000 n access 1000 n_misses 100 double n_access public long getNumNextLevelAccess return this n_access_to_next_level public long getNumWriteThrou
16. executa a simula o e actualiza a interface gr fica RunProgram por sua vez os inputs do utilizador na interface s o passados para esta thread controlando assim o modo de vizualiza o velocidade etc package cacheSim import java awt Dimension import java awt Point Classe que representa a thread de simula o Tem referencias interface principal para a poder actualizar Por usa vez a interface principal pode alterar o estado desta thread author Manuel EJ public class SimulationThread extends Thread private RunProgram window private boolean pause private boolean stepinto private boolean playmode private int sleepTime private SimParams params private final int SILENT MODE 200 MemAccessFile maf private boolean terminateThread public SimulationThread RunProgram window SimParams simParams this window window this pause true this playmode false this stepinto false this sleepTime window getSleepTime terminateThread false setParams simParams try maf new MemAccessFile simParams getTraceFile catch Exception e public void setParams SimParams simParams this params simParams window myCanvas setParams simParams this setPause true public void setPlayMode boolean mode this playmode mode public void run while terminateThread Alter the animation control variables for the n
17. for int i20 i n itt Block b cs getBlock i if b isClean int block_size sim getSplitCache getICache getBlockSize g drawString FIFO Order newest fifo b getFIFOindex this blockSelected x 4 block size bb x this blockSelected y bb y i bb y 3 g drawString LRU Order newest lru b getLastAccessTime this blockSelected x 4 32 bb x block size bb x this blockSelected y bb y i bb y 3 T T Jelsel CacheSet cs sim getSplitCache getDCache getCacheSet this selected set index int n cs getNBlocks long newest fifo 0 long newest lru 0 for int i20 i n itt long fifo cs getBlock i getFIFOindex long lru cs getBlock i getLastAccessTime if fifo newest fifo newest fifo fifo if lru newest lru newest lru lru T for int i20 i n itt Block b cs getBlock i if b isClean int block_size sim getSplitCache getDCache getBlockSize g drawString FIFO Order newest fifo b getFIFOindex this blockSelected x 4 block size bb x this blockSelected y bb y i bb y 3 g drawString LRU Order newest lru b getLastAccessTime this blockSelected x 4 32 bb x block size bb x this blockSelected y bb y i bb y 3 T T Jelse if sim isUnifiedCache int nsets nsets sim getUnifiedCache getUCache getAssociatividade g setColor Color B
18. if ma isDataWriteAccess amp amp cache this lastUsedSet Index getLastAccessedBlock isDirty cache this lastUsedSet Index getLastAccessedBlock lastDirtyMemAccess ma get Copy N o altera o conteudo da cache apenas determina a tag para um determinado acesso param ma return 28 116 Arquitectura Avan ada de Computadores Simulador de Cache x public long getTag MemAccess ma long tag ma getAddress gt gt this index size bits this block size bits return tag public int getTagBits return 32 this block size bits this index size bits public int getIndexBits return this index size bits public int getOffsetBits return this block size bits public CacheSet getCacheSet int index return this cache index public long getOffset MemAccess ma long a ma getAddress a a gt gt this block size bits a a lt lt this block size bits long offset ma getAddress a return offset public int get Index MemAccess ma long a ma getAddress a a gt gt this block size bits int set int a 8 this sets return set private int doDataReadAccess MemAccess ma long a ma getAddress a a gt gt this block size bits int set int a this sets this lastUsedSetIndex set long tag ma getAddress gt gt this index size bits this block size bits int acc cachelsetl doDataReadAccess
19. Aj public RunProgram super initialize This method initializes this Qreturn void ey private void initialize this setVisible false this setDefaultCloseOperation JFrame EXIT ON CLOSE this setJMenuBar getJJMenuBar this setSize 800 600 this setContentPane getJContentPane this setTitle my Cache Simulator this nextLevelDialog new NextLevelAccessDialog this nextLevelDialog setVisible false This method initializes jContentPane Qreturn javax swing JPanel xy private JPanel getJContentPane if jContentPane null jContentPane new JPanel jContentPane setBorder BorderFactory createEmptyBorder 5 5 5 5 jContentPane setLayout new BorderLayout jContentPane add getJPanelToolbar java awt BorderLayout NORTH jContentPane add getJPanelLegenda java awt BorderLayout SOUTH jContentPane add getJPanelEstatisticas java awt BorderLayout EAST jContentPane add getScrollPaneCanvas java awt BorderLayout CENTER return jContentPane This method initializes jJMenuBar Qreturn javax swing JMenuBar 7 private JMenuBar getJJMenuBar 1 if jJMenuBar null jJMenuBar new JMenuBar jJMenuBar add getFileMenu jJMenuBar add getHelpMenu return jJMenuBar 74 116 Arquitectura Avan ada de Computadores Simulador de Cache This method initializes jMenu return javax swin
20. acesso e para sabes se ja acabou Gauthor Manuel 0x F HF xXx public class MemAccessFile private BufferedReader br Representa o ficheiro com os acessos a mem ria iparam file ficheiro x public MemAccessFile String file throws FileNotFoundException br new BufferedReader new FileReader file public boolean hasMore try if br ready return false else return true catch Exception e return false public MemAccess getNext throws IOException MemAccess MemAccessFormatException return new MemAccess br readLine Recome a do inicio do ficheiro Qthrows IOException xA public void reset throws IOException br reset public void close throws IOException br close Demonstrag o do MemAccessFile param args string com o ficheiro a ser lido y public static void main String args 50 116 Arquitectura Avan ada de Computadores Simulador de Cache TODO Auto generated method stub try MemAccessFile maf new MemAccessFile d Manuel eclipse_workspace AAC cacheSim trace txt MemAccessFile maf new MemAccessFile args 0 while maf hasMore MemAccess ma maf getNext System out println ma toString T catch Exception e System out println e e printStackTrace 51 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 8 MyPoint Cl
21. es int blocks i cache getNumBlocks int block size i cache getBlockSize g setColor Color LIGHT GRAY g drawString block cl x X IND BLOCK 35 cl y 5 bsizel x bb x block size bsizel y bb y for int i 0 i blocks i if i cache getBlock i isClean g setColor Color GREEN g drawString empty cl x cl y bb y Jelsel g setColor Color BLACR 39 116 Arquitectura Avan ada de Computadores Simulador de Cache g drawString i cache getBlock i getTag cl x cl y bb y bb y i 3 i bsizel i bsizel i 10 bb i 10 bb x bb y x bb y y y print block status g setColor new Color 255 240 222 g setColor new Color 150 150 150 g fillRect cl x X_IND_BLOCK cl y bb y g setColor Color GRAY g drawRect cl x X IND BLOCK cl y bb y print dirty bit status if i cache getBlock i isDirty g setColor new Color 200 0 0 else g setColor Color LIGHT GRAY g fillRect cl x X IND BLOCK 10 cl y bb y g setColor Color GRAY g drawRect cl x X IND BLOCK 10 cl y bb y determina at onde vai a cache de instru es c2 y cl y bb y i RK RR RE RR EE RE RR RR RE Kk Ck CK Ck Ck Ck Ck Kk Ck Ck kk kk Ck ko kk RR RX RR XX A XX A RA E DESENHO CACHE DE DADOS RK RR RE RR RR RE RR RR aa RE RE RR RR RE RX EE RX RR XX RX RR RX J block size bb x bb y i ST G2 y 5 c2 y 100
22. falhas compuls rias quanto mais se aumenta a cache maiores s o as falhas iniciais Ent o ser de esperar para testes relativamente mais longos que as diferen as aumentem significativamente A rela o das taxas de falha entre a cache unificada e cache separada muito pr xima o que seria de esperar visto que tem o mesmo tamanho Outra evidencia que aumenta a confian a o facto de que a soma entre o n mero de falhas e n mero de acertos resulta no n mero total de acessos 2 5 2 Algoritmos de substitui o Z Outro teste que se pode realizar o da verifica o da efic cia dos algoritmos de substitui o para este teste realizam se os mesmos 10000 acessos para uma cache unificada tamanho 16KB tamanho do bloco 64 bytes associatividade 4 e pol tica de escrita write back P o de Misses next level Hits substituic o LRU 3370 4129 6630 Unified Cache FIFO 3462 4216 6538 Random 3757 4651 6243 Estes testes mostram o que era esperado a pol tica de substitui o mais eficaz a LRU seguida da FIFO e por fim RANDOM A maneira de funcionamento destas pol ticas comprovada empiricamente com aux lio da interface gr fica para cada acesso pode se ver o estado das vari veis usadas no c lculo do bloco a substituir Esses valores mostram a diferen a em nanosegundos ao bloco que a pol tica de substitui o considera mais recente Como se trata de um algoritmo simples e ap s verifica o na in
23. if escrita Cache WR_INSTR_CACHE return true else return false String associatividadeToString if associatividade blocks return direct mapping else return this associatividade public String toString return Cache size sizet bytes associativity tassociatividadeToString this blocks this associatividade sets size this block size bytes policy replacePolicyToString blocks this blocks write policy writePolicyToString replace block 31 116 Arquitectura Avan ada de Computadores Simulador de Cache preciso dizer qual o acesso a mem ria para determinar o conjunto que foi acedido em ultimo lugar so se pode chamar esta fun o depois de fazer o acesso a mem ria public int getLastAccessBlockIndex int index cache this lastUsedSetIndex getLastAccessedBlockIndex return lastUsedSetIndex this associatividade index determina o set a ser escolhido atraves do acesso a mem ria public int getSetIndex MemAccess ma long a ma getAddress a a gt gt this block size bits return int a this sets public int getAssociatividade return this associatividade pode retornar null caso n o haja acesso ao pr ximo nivel de mem ria public MemAccess getNextLevelAccess return this nextLevelAccessArray public static class CacheFormatException extends Exception static final long seria
24. long getNumAccess return iCache getNumAccess dCache getNumAccess long getNumHits return iCache getNumHits dCache getNumHits long getNumMisses return iCache getNumMisses dCache getNumMisses long getNumWriteThroughs return dCache getNumWriteThroughs iCache getNumWriteThroughs long getNumWriteBacks 1 return dCache getNumWriteBacks iCache getNumWriteBacks long getNumIAccess return dCache getNumIAccess iCache getNumIAccess long getNumDRAccess return dCache getNumDRAccess iCache getNumDRAccess long getNumDWAccess return dCache getNumDWAccess iCache getNumDWAccess long getNumNextLevelAccess return dCache getNumNextLevelAccess iCache getNumNextLevelAccess retorna o indice do ultimo bloco a ser acedido public int getLastAccessBlockIndex if this lastUsedCache 0 return iCache getLastAccessBlockIndex else return dCache getLastAccessBlockIndex 85 116 Simulador de Cache Arquitectura Avan ada de Computadores Simulador de Cache public int getLastUsedCache return this lastUsedCache public int getSetIndex MemAccess ma if ma isInstructionAccess return iCache getSetIndex ma else return dCache getSet Index ma if retorna o index do bloco ao qual pertence o primeiro set public int getSetBlockIndex MemAccess ma if ma isInstructionAccess return iCa
25. long serialVersionUID 0 JPanel jContentPane null JPanel jPanelCenter null JPanel jPanel null JLabel jLabel null JTextField jTextFieldTraceFile null JButton jButtonOpenFile null JPanel jPanell null JPanel jPanel2 null JTextField jTextFieldBlockSize null JPanel jPanel3 null JTextField jTextFieldSize null JPanel jPanel4 null JTextField jTextFieldAssociatividade null JLabel jLabel4 null JLabel jLabel5 null JLabel jLabel6 null JPanel jPanel5 null JComboBox jComboBoxReplacePolicy null JPanel jPanel6 null 103 116 Arquitectura Avan ada de Computadores Simulador de Cache private JLabel jLabell null private JPanel jPanel7 null private JLabel jLabel3 null private final Dimension labelDim new Dimension 100 25 private JPanel jPanel8 null private JLabel jLabel2 null private JPanel jPanel9 null private JLabel jLabel7 null private JPanel jPanell0 null private JPanel jPanelll null private JLabel jLabel8 null private JComboBox jComboBoxWritePolicy null private JPanel jPanell2 null private JButton jButtonCancel null private JButton jButtonOK null private RunProgram mainFrame private JCheckBox jCheckBoxRegistry null This is the default constructor SI public UnifiedCacheDialog RunProgram frame super frame true initialize this setTitle New Simulation
26. menor mais antigo Estas fun es s o sempre chamadas independentemente das pol ticas de substitui o escrita escolhidas apenas actualizam as vari veis necess rias para depois se conseguir processar uma pol tica de substitui o escrita N o est percept vel no diagrama da Figura 4 mas quando existe um acesso de escrita em que a pol tica de escrita write back o dirty bit do bloco correspondente colocado a true 2 4 Detalhes de implementa o A figura seguinte mostra uma vers o simplificada das classes seus atributos e opera es Como se pode ver o c digo est bastante modular e facilmente compreens vel Existem outras classes de suporte por exemplo janelas de di logo que apesar de terem alguma import ncia iriam dificultar a compreens o da organiza o global myCanvas MainCanvas SimulationThread animationThread SimulationThread o Ps MemAccessFile rit AS window PunProgram setupSimThread params SimParams params SimParams MemaAccessFile TsetSpeed speed int setPause b boolean hasMore getNext 7 SplitCache SimParams iCache Cache splitCache SplitCache dCache Cache unifiedCache UnifiedCache l V doMemAccess ma MemAccess traceFile String cacheType int S I isUnifiedCache UnifiedCache f iedCache isSplitCache uCache Cache doMemAccess ma MemAccess Cache cache CacheSet C
27. method initializes jPanell9 return javax swing JPanel REA private JPanel getJPanell9 if jPanell9 null jLabell4 new JLabel jLabell4 setText bytes jPanell9 new JPanel new FlowLayout FlowLayout LEFT jPanell9 add getJPanel20 null jPanelli9 add getJTextField5 null jPanell9 add jLabell4 null return jPanell9 This method initializes jPanel20 return javax swing JPanel we private JPanel getJPanel20 if jPanel20 null jLabell3 new JLabel jLabell3 setText block size jPanel20 new JPanel jPanel20 setPreferredSize labelDim jPanel20 add jLabell3 null return jPanel20 This method initializes jTextField5 return javax swing JTextField private JTextField getJTextField5 if jTextField5 null jTextField5 new JTextField jTextField5 setColumns 10 jTextField5 setText 64 return jTextField5 This method initializes jPanel21 return javax swing JPanel private JPanel getJPanel21 if jPanel21 null jPanel21 new JPanel new FlowLayout FlowLayout LEFT jPanel21 add getJPanel22 null jPanel21 add getJComboBoxReplacePolicyICache null return jPanel21 This method initializes jPanel22 98 116 Arquitectura Avan ada de Computadores Simulador de Cache return javax swing JPanel REA private JPanel getJPanel22 if jPanel2
28. metros necess rios simula o entre os quais a cache SplitCache ou UnifiedCache qual o tipo de cache usado e o ficheiro com os acessos package cacheSim Classe que tem os parametros obrigat rio para correr a simula o Capaz de dizer se a cache escolhida do tipo author Manuel y public class SimParams private SplitCache splitCache private UnifiedCache unifiedCache private String traceFile public static final int U_CACHE public static final int S_CACHE public int cacheType public SimParams SplitCache cache this splitCache cache this unifiedCache null this traceFile fileName t his cacheType S CACHE public this unifiedCache this splitCache null this traceFile fileName this cacheType U CACHE cache public boolean isUnifiedCache if cacheType U_CACHE return true else return false public boolean isSplitCache if cacheType S CACHE return true else return false public SplitCache getSplitCache return this splitCache public return this unifiedCache public String getTraceFile return this traceFile SimParams UnifiedCache cache String UnifiedCache getUnifiedCache Split ou Unified por exemplo fileName String fileName 76 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 12 SimulationT hread E uma das classes mais importantes do programa
29. new JLabel jLabell setText to see the entire list save to a file first jLabell setForeground new java awt Color 204 0 0 jLabel new JLabel jLabel setText Only shows the last 100 next level access jLabel setForeground new java awt Color 204 0 0 jPanel new JPanel new BorderLayout jPanel setBackground new java awt Color 241 242 245 56 116 Arquitectura Avan ada de Computadores Simulador de Cache jPanel add jLabel BorderLayout NORTH jPanel add jLabell BorderLayout SOUTH return jPanel 57 116 Arquitectura Avan ada de Computadores 6 2 10 RunProgram um dos tipos de Cache SplitCache ou UnifiedCache para simula es maiores janela principal Esta classe tamb m contem um objecto do tipo Simulation Thread que processa a simula o e tem um objecto do tipo MainCanvas adicionado sua parte gr fica para poder A classe que arranca o programa embora seja poss vel executar em modo consola cada E uma classe que extende JFrame e que contem todos os componentes gr ficos da renderizar o estado da cache e ver a simula o a correr package cacheSim import import import import import import import import import import import import import import import import import import import EE OR XBox Ver manual do utilizador Cria destroi a thread de Gauthor Manuel java awt event ActionListener java awt event ActionEven
30. o2 V V V doDataReadAccess doInstructionAccess doDataWriteAccess cacular tag calcular conjunto tag existe tag n o existe v blocos livres b conjunto cheio2 setAccessTime v LRU O escolhe bloco n o dirty dirty I QOO prece setAccessTime etCreati ime setCreationTime EL cesso a nivel superior de memoria write back write through V setAccessTime setCreationTime escolhe bloco clean false escolhe bloco hit miss acesso a nivel superior de memoria le Figura 4 Algoritmo de simula o O diagrama est bastante f cil de perceber mas conv m mencionar algumas fung es utilizadas setAccess Time e setCreationTime s o fun es que guardam o tempo corrente em nanosegundos numa vari vel do bloco poss vel utilizar a pol tica de substitui o LRU para determinar o bloco mais tempo inutilizado porque sempre que um bloco utilizado chama se a fun o setAccessTime assim s comparar e determinar quem tem o setAccessTime menor mais antigo A fun o setCreationTime guarda o tempo corrente numa vari vel do bloco quando usado pela primeira vez miss serve para determinar o bloco mais antigo em rela o data da 5 116 Arquitectura Avan ada de Computadores Simulador de Cache sua cria o assim simples de implementar a pol tica de substitui o FIFO bastando verificar quem tem o setCreation Time
31. pause TODO Auto generated Event stub actionPerformed if animationThread null animationThread pauseAnimation animationThread setPlayMode true n return jButtonPause This method initializes jButtonStepInto Qreturn javax swing JButton x private JButton getJButtonStepInto if jButtonStepInto null jButtonStepInto new JButton jButtonStepInto new JButton createImageIcon step gif oh yaeaH jButtonStepInto setEnabled false jButtonStepInto setText next step jButtonStepInto addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e RunProgram this jSliderSpeed setValue 1 System out println stepInto TODO Auto generated Event stub actionPerformed RunProgram this animationThread setStepInto true RunProgram this animationThread setPlayMode true RunProgram this animationThread setPause true return jButtonStepInto This method initializes jPanel return javax swing JPanel f private JPanel getJPanel if jPanelToolbarControls null jPanelToolbarControls new JPanel new FlowLayout FlowLayout LEFT jPanelToolbarControls add getJButtonPlay jPanelToolbarControls add getJButtonPause 64 116 Arquitectura Avan ada de Computadores Simulador de Cache jPanelToolbarControls add getJButtonStepInto jPanelToolbarControls add getJSli
32. return blocks index param tag param substPolicy return 0 tag igual 1 tag diferente n o dirty empty ox F xXx dirty public int doInstructionAccess long tag int substPolicy verifica se a instru o est num dos blocos for int i 0 i lt n blocks i if blocks i hasTag tag 2 tag diferente blocks i setAccessTime hit tempo para o LRU this lastAccessedBlockIndex i return 0 T verifica se existem blocos livres pode contar ou n o falhas compulsorias 33 116 Arquitectura Avan ada de Computadores Simulador de Cache for int i 0 i lt n blocks i verifica se existe algum bloco limpo if blocks i isClean blocks i tag tag blocks i clean false blocks i dirty bit false blocks i setAccessTime blocks i setCreationTime FIFO index this lastAccessedBlockIndex i return 1 return 0 se for para eliminar falhas compuls rias return 1 se contar com tudo politica de substitui o switch substPolicy case Cache S RANDOM return l randomSubst tag case Cache S LRU return l lruSubst tag case Cache S FIFO return 1 fifoSubst tag default System out println CacheSet doInstructionAccess N o devia acontecer isto return 9999999 param tag param substPolicy Qparam writePolicy return 0 tag igual 1 tag diferente n o dirty empty 2 tag difer
33. size jPanell6 new JPanel jPanell6 setPreferredSize labelDim jPanell6 add jLabel9 null return jPanell6 This method initializes jTextField3 return javax swing JTextField private JTextField getJTextField3 if jTextField3 null jTextField3 new JTextField jTextField3 setColumns 10 jTextField3 setText 16 return jTextField3 This method initializes jPanell7 return javax swing JPanel ERA private JPanel getJPanell7 if jPanell7 null jLabell2 new JLabel jLabell2 setText number of blocks per set jPanell7 new JPanel new FlowLayout FlowLayout LEFT jPanell7 add getJPanell18 null jPanell7 add getJTextField4 null jPanell7 add jLabell2 null return jPanell7 This method initializes jPanell8 return javax swing JPanel private JPanel getJPanell18 if jPanell8 null jLabelll new JLabel jLabelll setText associativity jPanell8 new JPanel jPanell8 setPreferredSize labelDim jPanell8 add jLabelll null return jPanell8 97 116 Arquitectura Avan ada de Computadores Simulador de Cache This method initializes jTextField4 return javax swing JTextField xf private JTextField getJTextField4 if jTextField4 null jTextField4 new JTextField jTextField4 setColumns 10 jTextField4 setText 2 return jTextField4 This
34. void actionPerformed java awt event ActionEvent e try int i_kb Integer parselnt jTextField3 getText int i_sets Integer parseInt jTextField4 getText int i block Integer parseInt jTextField5 getText int i sub MyItem jComboBoxReplacePolicyICache getSelectedItem value int d kb Integer parseInt jTextField getText int d sets Integer parseInt jTextFieldl getText int d block Integer parseInt jTextField2 getText int d wr MyItem jComboBoxWritePolicy getSelectedItem value int d sub MyItem jComboBoxReplacePolicy getSelectedItem value Cache iCache new Cache i kb i block i sets i sub Cache WR INSTR CACHE true Cache dCache new Cache d kb d block d sets d sub d wr true SplitCache sCache new SplitCache iCache dCache SimParams simParams new SimParams if jTextFieldTraceFile getText compareTo 0 WarningDialog wd new WarningDialog SplitCacheDialog this Warning nYou have to select a compatible trace file n nUse the button to find it wd setVisible true else mainFrame setNextLevelRegistry jCheckBoxNextLevelReg isSelected mainFrame setupSimThread new SimParams sCache jTextFieldTraceFile getText 92 116 Arquitectura Avan ada de Computadores Simulador de Cache mainFrame setReadyStatus true SplitCacheDialog this setVisible false catch Exception exc WarningDial
35. void pauseAnimation pause pause if pause window setStatusMessage Paused else window setStatusMessage Running 83 116 Arquitectura Avan ada de Computadores Simulador de Cache public void stopThread this terminateThread true 84 116 Arquitectura Avan ada de Computadores 6 2 13 SplitCache Esta classe representa uma cache do tipo separada tem duas vari veis que representam uma cache de i tornar a utiliza o mais transparente para o programador Assim agrupa se as duas caches numa nstru es e uma cache de dados A constru o desta classe tem como prop sito s classe evitando refazer certas partes do c digo package cacheSim Representa uma cache separada cache de dados mais cache de instrug es Esta classe executavel para poder correr simulag es pesadas Qauthor Manuel Maia bE public class SplitCache private private private private public throws public public public public public public public public public public Cache iCache Cache dCache int lastUsedCache 0 para iCache 1 para dCache MemAccess lastMemAccess SplitCache Cache iCache Cache dCache Exception if iCache isInstrCache throw new Exception iCache isn t an instruction cache this iCache iCache this dCache dCache MemAccess getLastMemAccess return this lastMemAccess
36. 2 null jLabell5 new JLabel jLabell5 setText replace policy jPanel22 new JPanel jPanel22 setPreferredSize labelDim jPanel22 add jLabell5 null return jPanel22 This method initializes jComboBox return javax swing JComboBox y private JComboBox getJComboBoxReplacePolicyICache if jComboBoxReplacePolicyICache null jComboBoxReplacePolicyICache new JComboBox jComboBoxReplacePolicyICache addItem new MyItem LRU Cache S LRU jComboBoxReplacePolicyICache addItem new MyItem Random Cache S RANDOM jComboBoxReplacePolicyICache addItem new MyItem Fifo Cache S FIFO return jComboBoxReplacePolicyICache This method initializes jPanel23 return javax swing JPanel x private JPanel getJPanel23 if jPanel23 null jPanel23 new JPanel new FlowLayout FlowLayout LEFT jPanel23 add getJPanel24 null jPanel23 add getJComboBoxWritePolicyICache null return jPanel23 This method initializes jPanel24 return javax swing JPanel private JPanel getJPanel24 if jPanel24 null jLabell6 new JLabel jLabell6 setText write policy jPanel24 new JPanel jPanel24 setPreferredSize labelDim jPanel24 add jLabell6 null return jPanel24 This method initializes jComboBoxl Qreturn javax swing JComboBox xf private JComboBox getJComboBoxWritePolicyICache if jComboBox
37. 39 5 24 Decimal Address tag 23 bits index 3 bits offset 6 bits 3821 l Estatisticas 2088950 2088844 Acessos ae ooo 2088944 Cache Hits 1001 3822 Cache Misses mero 0 Write Throughs 0 Write backs EESTI Next Level HS 2294 1196110 4850 E 3823 2096829 2096828 1554815 1555134 2088946 1179535 E 1048847 3839 2096831 4543 Acessos 1573887 Instructions 1411 1708031 Data Reads Bro iv Data Writes 1114 T gt Paused Show Next Level Access resultado do acesso Tamb m poss vel ver em que parte do bloco o acesso diz respeito e qual o tipo de acesso feito Outra op o a defini o da velocidade de anima o esta velocidade s interessa se a simula o estiver em modo play 16 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 1 5 Acessos ao pr ximo n vel de mem ria A interface disp e de um bot o situado no canto inferior direito que permite ver os acessos ao pr ximo n vel de mem ria salva acessos para ficheiro de esconde a janela texto amp Next Level Access Save to file Esta janela s mostra os ltimos 100 acessos por uma quest o de efici ncia mas ao guardar para um ficheiro s o escritos todos os acessos ao pr ximo n vel de mem ria 17 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 C digo As cla
38. D BLOCK 10 cl y bb y i 10 bb y determina at onde vai a cache de instru es GE tl y Bbw S EEK K k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k kk k kkk k kkk kkk k DESENHO DO CONJUNTO x S EEK K k k kk k k RR RE RR kk Ck CK Ck Ck RR KC k k k k k k k k k ko kk k k k k k k k k kk k kkk k k kk k if this isBlockSelected if sim isSplitCache int nsets if this cacheSelected 0 nsets sim getSplitCache getICache getAssociatividade else nsets sim getSplitCache getDCache getAssociatividade g setColor Color BLACK g drawRect this blockSelected x X IND BLOCK 5 this blockSelected y this blockSelectedSize x X IND BLOCK 5 this blockSelectedSize y nsets g drawRect this blockSelected x 1 X IND BLOCK 5 this blockSelected y 1 this blockSelectedSize x 2 X IND BLOCK 5 this blockSelectedSize y nsets 2 42 116 Arquitectura Avan ada de Computadores Simulador de Cache tentar imprimir as flags de LRU ou FIFO if this cacheSelected 0 CacheSet cs sim getSplitCache getICache getCacheSet this selected set index int n cs getNBlocks long newest fifo 0 long newest lru 0 for int i20 i n itt long fifo cs getBlock i getFIFOindex long lru cs getBlock i getLastAccessTime if fifo newest fifo newest fifo fifo if lru newest lru newest lru lru T
39. File null jPanel add getJButtonOpenFile null return jPanel This method initializes jTextFieldTraceFile return javax swing JTextField x private JTextField getJTextFieldTraceFile if jTextFieldTraceFile null jTextFieldTraceFile new JTextField jTextFieldTraceFile setColumns 20 return jTextFieldTraceFile This method initializes jButtonOpenFile return javax swing JButton private JButton getJButtonOpenFile if jButtonOpenFile null jButtonOpenFile new JButton jButtonOpenFile setText jButtonOpenFile addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e System out println actionPerformed TODO Auto generated Event stub actionPerformed JFileChooser chooser new JFileChooser System getProperty user dir Note source for ExampleFileFilter can be found in FileChooserDemo under the demo jfc directory in the Java 2 SDR Standard Edition int returnVal chooser showOpenDialog UnifiedCacheDialog this if returnVal JFileChooser APPROVE OPTION System out println You chose to open this filer NT chooser getSelectedFile getName System out println File chooser getSelectedFile getAbsolutePath 105 116 Arquitectura Avan ada de Computadores Simulador de Cache UnifiedCacheDialog this jTextFieldTraceFile setText c
40. I RR RAR A g fillRect 0 5 90 21 g setColor Color WHITE g drawString Unified Cache 10 20 g setColor Color BLACK g fillRect 0 c1 y 32 120 15 g setColor Color WHITE g drawString unified cache cl x cl y 20 g setColor Color LIGHT GRAY g drawString tag Arey Olr Ay OLYE 5 Cache u cache sim getUnifiedCache getUCache desenha a cache de instru es int blocks u cache getNumBlocks int block size u cache getBlockSize g setColor Color LIGHT GRAY g drawString block cl x X IND BLOCK 35 block size bb x cl y 5 bsizel x bb x block size bsizel y bb y for int i 0 i blocks i if u cache getBlock i isClean g setColor Color GREEN 41 116 Arquitectura Avan ada de Computadores Simulador de Cache g drawString empty cl x cl y Err bbw P SEJ else g setColor Color BLACK g drawString u cache getBlock i getTag cl x cl y bb y bb y i 3 T print block status g setColor new Color 255 240 222 g setColor new Color 150 150 150 g fillRect cl x X IND BLOCK cl y bb y i bsizel x bb y g setColor Color GRAY g drawRect cl x X IND BLOCK cl y bb y i bsizel x bb y print dirty bit status if u cache getBlock i isDirty g setColor new Color 200 0 0 else g setColor Color LIGHT GRAY g fillRect cl x X IND BLOCK 10 cl y bb y 4 5 10 bb y g setColor Color GRAY g drawRect cl x X IN
41. JPanell if jPanell null jLabel new JLabel jLabel setText Arquitectura Avan ada de Computadores 2005 2006 jLabel setForeground java awt Color white jPanell new JPanel jPanell setBackground new java awt Color 204 51 0 jPanell setPreferredSize new java awt Dimension 306 36 jPanell add jLabel null return jPanell This method initializes jTextArea return javax swing JTextArea ef private JTextArea getJTextArea if jTextArea null jTextArea new JTextArea jTextArea setText FEUP 2005 n Este programa foi desenvolvido no mbito da cadeira de Arquitectura Avan ada de Computadores ano lectivo 2005 2006 n nDesenvolvido por nManuel Faria de Azevedo Maia nmail ei001288fe up pt Anhttp www fe up pt ei00128 index html n nDocente da disciplina nJoao Canas Ferreira nmail jcf fe up pt jTextArea setLineWrap true jTextArea setWrapStyleWord true jTextArea setBounds new java awt Rectangle 5 5 300 96 jTextArea setBackground java awt SystemColor text 20 116 Arquitectura Avan ada de Computadores Simulador de Cache return jTextArea This method initializes jScrollPane return javax swing JScrollPane x7 private JScrollPane getJScrollPane if jScrollPane null jScrollPane new JScrollPane jScrollPane setBorder javax swing BorderFactory createEmptyBorder 5 5 5 5
42. LACK g drawRect this blockSelected x X IND BLOCK 5 this blockSelected y this blockSelectedSize x X IND BLOCK 5 this blockSelectedSize y nsets 43 116 Arquitectura Avan ada de Computadores Simulador de Cache g drawRect this blockSelected x 1 X IND BLOCK 5 this blockSelected y 1 this blockSelectedSize x 2 X IND BLOCK 5 this blockSelectedSize y nsets 2 imprimi a ordem das flags para lru e fifo CacheSet cs sim getUnifiedCache getUCache getCacheSet this selected set index int n cs getNBlocks long newest fifo 0 long newest lru 0 for int i20 i n i long fifo cs getBlock i getFIFOindex long lru cs getBlock i getLastAccessTime if fifo newest fifo newest fifo fifo if lru newest lru newest lru lru for int i 0 i n i Block b cs getBlock i if b isClean int block_size sim getUnifiedCache getUCache getBlockSize g drawString FIFO Order newest fifo b getFIFOindex this blockSelected x 4 block size bb x this blockSelected y bb y i bb y 3 g drawString LRU Order newest lru b getLastAccessTime this blockSelected x 4 32 bb x block size bb x this blockSelected y bb y i bb y 3 T g setColor Color BLACK else imprime o bloco realmente escolhido if sim isSplitCache int i sim getSplitCache getLastAccessBlockInd
43. Listener public void actionPerformed java awt event ActionEvent e System out println actionPerformed TODO Auto generated Event stub actionPerformed SplitCacheDialog newSimDialog new SplitCacheDialog RunProgram this newSimDialog setVisible true Dm return jMenultemNewSim2 This method initializes jPanelSecundaryControls return javax swing JPanel REA private JPanel getJPanelSecundaryControls if jPanelSecundaryControls null jPanelSecundaryControls new JPanel jPanelSecundaryControls add getJButtonShowNextLevelAccess null return jPanelSecundaryControls This method initializes jButtonShowNextLevelAccess return javax swing JButton private JButton getJButtonShowNextLevelAccess if jButtonShowNextLevelAccess null jButtonShowNextLevelAccess new JButton jButtonShowNextLevelAccess setText Show Next Level Access jButtonShowNextLevelAccess addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e if RunProgram this nextLevelDialog isVisible RunProgram this nextLevelDialog setVisible false RunProgram this jButtonShowNextLevelAccess setText Show Next Level Access Jelsel RunProgram this nextLevelDialog setVisible true RunProgram this jButtonShovNextLevelAccess setText Hide Next Level Access return jButtonShowNextLevelAcces
44. O utilizador pode salvar esses acesso para um ficheiro maior rapidez na simula o author Manuel public class NextLevelAccessDialog extends JDialog public static final long serialVersionUID 0 private JPanel jContentPane null private JPanel jPanelControls null private JButton jButtonHide null private JButton jButtonSave null private JTextArea jTextArea null private ScrollPane scrollPane null private JPanel jPanel null private JLabel jLabel null private JLabel jLabell null This is the default constructor pis public NextLevelAccessDialog RunProgram frame super frame false initialize this setLocation frame getSize width 0 pr ximo nivel de mem ria Pode esconder a janela para private LinkedList lt MemAccess gt array new LinkedList MemAccess 53 116 Arquitectura Avan ada de Computadores Simulador de Cache This method initializes this Qreturn void m f private void initialize this setSize 270 600 this setContentPane getJContentPane this setTitle Next Level Access This method initializes jContentPane return javax swing JPanel REA private JPanel getJContentPane if jContentPane null jContentPane new JPanel jContentPane setLayout new BorderLayout jContentPane add getJPanelControls java awt BorderLayout NORTH jContentPane add getScrollPane java awt B
45. Panel new FlowLayout FlowLayout LEFT jPanel5 add getJPanel9 null jPanel5 add getJComboBoxReplacePolicy null return jPanel5 This method initializes jComboBoxReplacePolicy Qreturn javax swing JComboBox REA private JComboBox getJComboBoxReplacePolicy if jComboBoxReplacePolicy null jComboBoxReplacePolicy new JComboBox jComboBoxReplacePolicy addItem new MyItem LRU Cache S LRU 107 116 Arquitectura Avan ada de Computadores Simulador de Cache jComboBoxReplacePolicy addItem new MyItem Random Cache S RANDOM jComboBoxReplacePolicy addItem new MyItem Fifo Cache S FIFO return jComboBoxReplacePolicy This method initializes jPanel6 return javax swing JPanel REA private JPanel getJPanel6 if jPanel6 null jLabell new JLabel jLabell setText size jPanel6 new JPanel jPanel6 setPreferredSize labelDim jPanel6 add jLabell null return jPanel6 This method initializes jPanel7 return javax swing JPanel SL private JPanel getJPanel7 if jPanel7 null jLabel3 new JLabel jLabel3 setText associativity jPanel7 new JPanel jPanel7 add jLabel3 null jPanel7 setPreferredSize labelDim return jPanel7 This method initializes jPanel8 return javax swing JPanel 7 private JPanel getJPanel8 if jPanel8 null jLabel2 new JLabel jLabel2 setText
46. TextFieldNextLevel setBackground c1 this jTextFieldNextLevel setText next level if Long parseLong jTextFieldNextLevel getText next level this jTextFieldNextLevel setBacRground c2 else this jTextFieldNextLevel setBackground c1 this jTextFieldNextLevel setText next level X instruction access if Long parseLong jTextFieldIAccess getText i access this jTextFieldIAccess setBackground c2 else this jTextFieldIAccess setBackground cl this jTextFieldIAccess setText i access datawrite access if Long parseLong jTextFieldDRAccess getText dr access jTextFieldDRAccess setBackground c2 else jTextFieldDRAccess setBackground cl this jTextFieldDRAccess setText dr access if Long parseLong jTextFieldDWAccess getText dw access jTextFieldDWAccess setBackground c2 else jTextFieldDWAccess setBackground cl this jTextFieldDWAccess setText dw access catch Exception e System out println Exception e getMessage void setupSimThread SimParams params this nextLevelDialog clearList if animationThread null animationThread new SimulationThread RunProgram this animationThread start Jelsel try animationThread stopThread animationThread join catch Exception exc System out println exc getMessage T animationThread new SimulationThread RunProgram this animationThread setP
47. WritePolicyICache null jComboBoxWritePolicyICache new JComboBox jComboBoxWritePolicyICache addItem new MyItem none instruction cache 1 jComboBoxWritePolicyICache setEnabled false return jComboBoxWritePolicyICache 99 116 Arquitectura Avan ada de Computadores Simulador de Cache private class MyItem public int value public String desc public MyItem String descricao int value desc descricao this value value public String toString return desc This method initializes jCheckBoxNextLevelReg return javax swing JCheckBox EA private JCheckBox getJCheckBoxNextLevelReg if jCheckBoxNextLevelReg null jCheckBoxNextLevelReg new JCheckBox jCheckBoxNextLevelReg setText Next Level Access Log jCheckBoxNextLevelReg setSelected true jCheckBoxNextLevelReg addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e System out println actionPerformed TODO Auto generated Event stub actionPerformed if jCheckBoxNext LevelReg isSelected System out println Selected else System out println Not Selected Dm return jCheckBoxNextLevelReg Qjve decl index 0 visual constraint 10 10 100 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 15 UnifiedCache Representa uma cache unificada apesar de se puder usar directam
48. a o por meio de uma interface gr fica Nesta interface o utilizador pode ver a simula o em modo play que vai apresentado a sequ ncia de acessos a mem ria com a cad ncia especificada por defeito embora possa ser alterada usando a scroll bar presente na interface principal que serve para definir a velocidade da execu o da simula o Em complemento com a funcionalidade play poss vel pausar a simula o usando o bot o pause Outra funcionalidade o bot o next step com esta op o o utilizador pode simular um acesso a mem ria de cada vez Como se pode ver na Figura 1 teve se muito em conta a usabilidade e facilidade de utiliza o as op es principais est o bem vis veis e as estat sticas tamb m Outra funcionalidade ser executar a simula o em modo silencioso isto apresenta s as estat sticas durante o decorrer da simula o sem precisar de correr a simula o em modo gr fico completo que bastante lento e pode usar muitos recursos da m quina em que est a correr Para simula es muito grandes isto com v rios milh es de acessos aconselh vel correr em modo texto numa consola configurando a cache com passagem de argumentos Nestes argumentos est o o tamanho da cache o tamanho de bloco associatividade pol tica de substitui o pol tica de escrita e o nome do ficheiro de acessos Voltando interface gr fica o utilizador pode criar dois tipos de simula o uma para split cache e ou
49. acheSet Cache kb int block size int associatividade int blocks Block politica subst int politica escrita int Es 33 n blocks int doMemAccess ma Mem ccess doDataReadAccess ma Mem ccess doDataWriteAccess ma Mem ccess doInstructionAccess ma Mem ccess fifoSubst tag long lruSubst tag long randomSubst tag long tag long clean boolean dirty bit boolean last ccess loong creationTime long Figura 5 Organiza o do c digo em classes A classe RunProgram utiliza e controla a SimulationThread e por sua vez a SimulationThread actualiza a componente gr fica do programa 6 116 Arquitectura Avan ada de Computadores Simulador de Cache A SimulationThread corre a simula o chamando consecutivamente a fun o getNext da classe MemAccessFile que devolve o pr ximo acesso devidamente constru do e representado pela classe MemAccess n o representada neste diagrama Para realizar o acesso a SimulationThread determina qual o tipo de simula o que est a correr a partir do SimParams e chama a fun o doMemAccess Como se pode ver a cache est organizada num array de CacheSet que representa conjuntos grupos de blocos e por sua vez a CacheSet contem um array de blocos que s o o elemento base da cache Depois de correr o acesso a SimulationThread chama a fun o repaint do objecto myCanvas do tipo MainCanvas localizado na classe RunProgram Este
50. acks B dit Next Level 3124 2294 1196110 450 E 3823 2096829 2096828 1554815 1555134 2088946 1179535 bloco gt FIFO Order O LRU Order 0 FIFO Order 805585626 LRU Order 23511927 escolhido 7096831 4543 Acessos 1573887 Instructions 1411 1708031 Data Reads 936 m Data Writes 1114 Ju gt paeme Paused Show Next Level Access T qual a ordem para cada uma das politicas de substitui o ver os acessos ao pr ximo nivel de mem ria quanto menor mais recente valores elevados porque usou se nanosegundos diferen a 15 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 1 4 Resultado de um acesso Depois de executar um acesso o utilizador pode ver o resultado desse acesso Na parte das estat sticas pode ver a laranja os campos que foram incrementados uma unidade e os que est o a cinzento mantiveram se iguais Em algumas situa es por exemplo quando h um bloco que est dirty e faz se um acesso de leitura que n o tem a mesma tag acontece que existe dois acessos ao pr ximo n vel quando isso acontece o campo em vez de aparecer laranja aparece a vermelho resultado do acesso a laranja significa que incrementou uma unidade velocidade da anima o a vermelho significa que incrementou duas unidades Es my Cache Simulator EEES File Help 1 1 Gad Ed O o i Address 001DFF58 Access Type R Access Size 8 00000000000111011111111 101 011000 Binary Address 38
51. ada de Computadores Simulador de Cache jPanel add getJButtonOpenFile null return jPanel This method initializes jTextFieldTraceFile return javax swing JTextField REA private JTextField getJTextFieldTraceFile if jTextFieldTraceFile null jTextFieldTraceFile new JTextField jTextFieldTraceFile setColumns 20 jTextFieldTraceFile setEditable false jTextFieldTraceFile setBackground new Color 250 250 250 jTextFieldTraceFile setText return jTextFieldTraceFile This method initializes jButtonOpenFile return javax swing JButton 5j private JButton getJButtonOpenFile if jButtonOpenFile null jButtonOpenFile new JButton jButtonOpenFile setText jButtonOpenFile addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e System out println actionPerformed TODO Auto generated Event stub actionPerformed JFileChooser chooser new JFileChooser System getProperty user dir Note source for ExampleFileFilter can be found in FileChooserDemo under the demo jfc directory in the Java 2 SDR Standard Edition int returnVal chooser showOpenDialog SplitCacheDialog this if returnVal JFileChooser APPROVE OPTION System out println You chose to open this file chooser getSelectedFile getName System out println File chooser getSel
52. adores Simulador de Cache return javax swing JTextField iA private JTextField getJTextFieldCacheMiss if jTextFieldCacheMiss null jTextFieldCacheMiss new JTextField jTextFieldCacheMiss setText 0 jTextFieldCacheMiss setEditable false jTextFieldCacheMiss setBackground Color WHITE return jTextFieldCacheMiss This method initializes scrollPaneCanvas return java awt ScrollPane 7 private ScrollPane getScrollPaneCanvas if scrollPaneCanvas null scrollPaneCanvas new ScrollPane myCanvas new MainCanvas myCanvas createBufferStrategy 1 scrollPaneCanvas add myCanvas return scrollPaneCanvas This method initializes jSliderSpeed return javax swing JSlider private JSlider getJSliderSpeed if jSliderSpeed null jSliderSpeed new JSlider RunProgram MIN SLEEP RunProgram MAX SLEEP RunProgram START SLEEP jSliderSpeed setName Speed jSliderSpeed setToolTipText Defines the speed of the simulation bigger means slower simulation jSliderSpeed addChangeListener new javax swing event ChangeListener public void stateChanged javax swing event ChangeEvent e RunProgram this jTextFieldSpeed setText RunProgram this jSliderSpeed getValue if RunProgram this animationThread null RunProgram this animationThread setSpeed RunProgram this jSliderSpeed getValue Dm return jSliderSpeed This
53. an ada de Computadores Simulador de Cache public void setParams SimParams sim this sim sim if this sim isSplitCache int altura sim getSplitCache getICache getNumBlocks sim getSplitCache getDCache getNumBlocks Jelsel int largura sim getSplitCache getICache getBlockSize int largura sim getSplitCache getDCache getBlockSize if largura gt largura largura largura2 this setSize largura bb x 500 altura bb y 200 int altura sim getUnifiedCache getUCache getNumBlocks int largura sim getUnifiedCache getUCache getBlockSize this setSize largura bb x 500 altura bb y 200 public void paint Graphics 9 if sim null 1 desenho de uma cache de instru es if sim isSplitCache RK KKK IK RR RR RR RR RR RR RR RR RR RR RR RR RR RX A Vs DESENHO CACHE DE INSTRU ES RK KKK AR KK RR RR RR RR RR RR RR RR RR I I RR EX A block size bb x bb y i T g fillRect 0 5 80 21 setColor Color WHITE drawString Split Cache 10 20 Qa setColor Color BLACK fillRect 0 c1 y 32 120 15 setColor Color WHITE drawString Instruction cache cl x cl y 20 QUO 0 0 setColor Color LIGHT GRAY drawString tag direy elsz clvy 5 Q Q Cache i cache sim getSplitCache getICache Cache d cache sim getSplitCache getDCache desenha a cache de instru
54. arams params animationThread start this scrollPaneCanvas setScrollPosition 0 0 void setStatusMessage String s this jLabelStatus setText s int getSleepTime if this jSliderSpeed null return this jSliderSpeed getValue else return RunProgram START_SLEEP void setScrollPosition int x int y Dimension d this getthis scrollPaneCanvas getSize this scrollPaneCanvas setScrollPosition x y 100 params params 62 116 Arquitectura Avan ada de Computadores Simulador de Cache This method initializes jPanelToolbar return javax swing JPanel aA private JPanel getJPanelToolbar if jPanelToolbar null jPanelToolbar new JPanel new BorderLayout jPanelToolbar add getJPanel BorderLayout NORTH jPanelToolbar add getJPanelAccess java awt BorderLayout WEST jPanelToolbar add getJPanelAccessDecoded java awt BorderLayout SOUTH return jPanelToolbar This method initializes jPanelLegenda Qreturn javax swing JPanel sy private JPanel getJPanelLegenda if jPanelLegenda null jPanelLegenda new JPanel jPanelLegenda setLayout new BorderLayout jPanelLegenda add getJPanelStatus BorderLayout WEST jPanelLegenda add getJPanelSecundaryControls java awt BorderLayout EAST return jPanelLegenda This method initializes jButtonPlay return javax swing JButton REA private JButton getJButtonP
55. ario2 setText bitFormat index b2 jTextFieldOffset setText offset 60 116 Arquitectura Avan ada de Computadores Simulador de Cache this jTextFieldBinario3 setText bitFormat offset b3 private String bitFormat long n int n_bits String s Long toBinaryString n for int i 0 i lt n bits s length i while s length n bits s 0 s return s private String bitFormat int n int n_bits String s Integer toBinaryString n for int i 0 i lt n bits s length i while s length lt n bits Boe LOU 8 return sS public void resetStatistcsBackColor Color cl Color LIGHT GRAY his jTextFieldAcessos setBackground cl his jTextFieldCacheHits setBackground cl his jTextFieldCacheMiss setBackground cl his jTextFieldWriteThroughs setBackground c1 his jTextFieldWriteBacks setBackground c1 his jTextFieldNextLevel setBackground cl his jTextFieldIAccess setBackground cl his jTextFieldDRAccess setBackground cl his jTextFieldDWAccess setBackground cl Ct ct Ack tet Ch Er chy CE CE public void setStatistcs long acessos long hits long misses long wr_throughs long wr_backs long next_level long i_access long dr_access long dw_access Color cl Color LIGHT_GRAY Color c2 new Color 255 128 0 Color c3 new Color 255 0 0 try numero de acessos if Long parseLong this jTextFieldIAccess getText acessos this jTextFieldAcesso
56. asse utilit ria tanto pode representar uma coordenada como a dimens o de uma imagem 2D por exemplo package cacheSim Classe utilitaria Pode ser usada para representar um ponto coordenada tamanho de algum objecto 2D author Manuel 7 public class MyPoint public int x public int y public MyPoint int x int y this x x this y y 52 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 9 NextLevelAccessDialog Representa a janela que mostra os acessos ao pr ximo n vel de mem ria resultantes no decorrer da simula o Por uma quest o de performance s mostra os ltimos 100 acessos de cada vez Tem a possibilidade de guardar para um ficheiro todos os acessos no formato especificado no enunciado do trabalho Utiliza uma lista ligada para guardar os acessos e manter alguma performance de escrita e gest o din mica de mem ria package cacheSim import java awt BorderLayout import java awt FlowLayout import java awt Font import javax swing JDialog import javax swing JPanel import javax swing JButton import java awt ScrollPane import java io BufferedWriter import java io File import java io FileWriter import java io IOException import java util LinkedList import java util ListIterator import javax swing JFileChooser import javax swing JTextArea import javax swing JLabel Esta classe representa a janela que mostra os acesso ao
57. ax swing JTextField private JTextField getJTextFieldBinario if jTextFieldBinario null jTextFieldBinario new JTextField jTextFieldBinario setColumns 32 jTextFieldBinario setEditable false jTextFieldBinario setBackground Color WHITE jTextFieldBinario setFont new Font Courier New Font PLAIN 12 return jTextFieldBinario This method initializes jTextFieldBinario2 72 116 Arquitectura Avan ada de Computadores Simulador de Cache 12 12 return javax swing JTextField private JTextField getJTextFieldBinario2 if jTextFieldBinario2 null jTextFieldBinario2 new JTextField jTextFieldBinario2 setColumns 16 jTextFieldBinario2 setEditable false jTextFieldBinario2 setBackground Color WHITE jTextFieldBinario2 setFont new Font Courier New Font PLAIN return jTextFieldBinario2 This method initializes jTextFieldBinario3 return javax swing JTextField REA private JTextField getJTextFieldBinario3 if jTextFieldBinario3 null jTextFieldBinario3 new JTextField jTextFieldBinario3 setColumns 16 jTextFieldBinario3 setEditable false jTextFieldBinario3 setBackground Color WHITE jTextFieldBinario3 setFont new Font Courier New Font PLAIN return jTextFieldBinario3 This method initializes jTextFieldIndex return javax swing JTextField we private JTextField getJTextFieldInde
58. ce gr fica principal esta fica encarregue de lan ar uma thread que executa a simula o e que por sua vez desenha na interface principal A interface principal tem os controlos necess rios para pausar continuar e definir a velocidade da simula o A thread de simula o simplesmente encontra se num estado definido pela interface e age conforme o seu estado actual Se estiver pausada suspende a simula o se estiver em modo play continua a executar ininterruptamente a simula o ou se estiver em modo iterativo next step reproduz um acesso a mem ria e espera um input da interface gr fica que dado pelo utilizador quando carrega no bot o play step into Ps RunProgram _ SimulationThread IN 1 ficheiro de texto Figura 3 Arquitectura l gica 2 3 Algoritmos O algoritmo mais complexo usado neste programa a simula o do acesso a mem ria Como se pode ver no diagrama de fluxo da Figura 4 trata se de um processo complicado sobretudo na parte de substitui o do bloco A thread de simula o tem um objecto do tipo SplitCache ou UnifiedCache que aceitam acessos a mem ria representados pela classe MemAccess ver capitulo sobre detalhes da implementa o A partir da chamada fun o doMemAccess o acesso executado de acordo com o diagrama da Figura 4 4 116 Arquitectura Avan ada de Computadores Simulador de Cache determinar tipo de acesso leitura2 escrita2 busca de instru
59. cess this n datawrite access if this escrita Cache WR BACK ALLOCATE if ret 2 this n misses this n write backs this n access to next level 2 27 116 Arquitectura Avan ada de Computadores Simulador de Cache if ret 1 this n misses this n access to next level if ret 0 this n hits verificar isto com o professor escritas na cache causam hits ou misses ou nenhum dos dois jelse if this escrita Cache WR_THROUGH_NO_ALLOCATE this n write throughs this n access to next level else if ma isInstructionAccess this n instr access if ret 0 this n hits T if ret 1 this n access to next level this n misses if ret 2 his n_access_to_next_level 2 his n missestt verificar isto com o prof his n write backs ct ct ct regista os ultimos acessos a mem ria causou um miss e um write back if ret 2 this nextLevelAccessArray new MemAccess 2 this nextLevelAccessArray 0 cache this lastUsedSetIndex getLastAccessedBlock lastDirtyMemAccess getCopy this nextLevelAccessArray 1 ma getCopy causou s um miss if ret 1 this nextLevelAccessArray new MemAccess 1 this nextLevelAccessArray 0 ma getCopy if ret 0 this nextLevelAccessArray null se o bloco ficou dirty data write access entao memoriza o acesso que fez lo ficar dirty
60. che getSetIndex ma iCache getAssociatividade else return dCache getSetIndex ma dCache getAssociatividade public void doMemAccess MemAccess ma throvs Cache CacheFormatException this lastMemAccess ma getCopy if ma isInstructionAccess iCache doMemAccess ma this lastUsedCache 0 else dCache doMemAccess ma this lastUsedCache 1 public Cache getICache return iCache public Cache getDCache return dCache public static void main String args try if args length 6 System out println Wrong usage System out println java cacheSim SplitCache n t lt cache size KB gt n t lt block size n t lt associativity gt n t lt LRU FIFO RANDOM gt n t lt WR_BACK file gt System exit 0 int size Integer parseInt args 0 int block Integer parseInt args 1 int assoc Integer parseInt args 2 int sub 1 int wr 1 if args 3 compareTo LRU 0 sub Cache S_LRU if args 3 compareTo FIFO 0 sub Cache S_FIFO if args 3 compareTo RANDOM 0 sub Cache S_RANDOM if args 4 compareTo WR BACK 0 wr Cache WR BACK ALLOCATE if args 4 compareTo WR THROUGH wr Cache WR THROUGH NO ALLOCATE bytes gt WR_THROUGH gt n t lt trace 86 116 Arquitectura Avan ada de Computadores Simulador de Cache Cache WR INSTR CACHE e getMessage Cache S
61. cionamento de uma cache e qual o seu objectivo O principal objectivo deste trabalho a partir de um conjunto de acessos a mem ria verificar a efic cia de uma determinada arquitectura de cache A partir desse conjunto de acessos que est o descritos num ficheiro deve ser poss vel simular o funcionamento da cache sendo as caracter sticas da mesma especificada pelo utilizador e obter estat sticas relevantes que demonstrem a efic cia da cache A simula o tem como objectivo medir os seguintes par metros o N mero de acessos a mem ria mostrando quantos acessos de cada tipo leitura escrita ou busca de instru o o N mero de acertos hits e falhas misses o N mero de write backs ou write throughs o Acessos ao n vel superior Outro objectivo o de correr a simula o em modo gr fico iterativo Isto significa que o utilizador pode correr a simula o passo a passo e ver o estado da cache mudar consoante se realizem acessos Tamb m pode aumentar e diminuir a velocidade de simula o durante o decorrer da simula o 1 116 Arquitectura Avan ada de Computadores Simulador de Cache 2 Descri o Nesta sec o descreve se com algum detalhe algumas funcionalidades do programa seguido por mais pormenores de algumas op es tomadas como a arquitectura algoritmos e detalhes da implementa o 2 1 Funcionalidades Este programa tem como principal funcionalidade a visualiza o iterativa da simul
62. croll y gt p y amp amp scroll_y lt p y d height window scrollPaneCanvas setScrollPosition 0 scroll y 100 window myCanvas repaint para a simula o at step into do Thread sleep sleepTime while this stepinto amp amp pause amp amp terminateThread this stepinto false window myCanvas removeBlockSelected params getUnifiedCache doMemAccess ma MemAccess array params getUnifiedCache getUCache getNextLevelAccess if array null for int i 0 i array length i window addNextLevelAccess array i ERRADO RR KK e kx KK KK KK window setNextTag params getSplitCache getICache getTag ma int scroll_y params getUnifiedCache getSetIndex ma window myCanvas getBlockByteDrawSize y window setScrollPosition 0 scroll_y Thread sleep sleepTime params getUnifiedCache doMemAccess ma ok ke RR RR XXX tem que estar aqui para n o fazer repaint quando n o deve window myCanvas repaint showStatistcs else this setPause true window setStatusMessage Simulation finished catch Exception e 82 116 Arquitectura Avan ada de Computadores Simulador de Cache formato errado te getMessage WarningDialog window System out println Thread gt Acesso com o WarningDialog dial new Error Bad Access Format Ignoring access Mn te getMessage dial setVisible true Je
63. dTop LabelBits null null null public void setNextLevelRegistry boolean b this nextLevelRegistry b ButtonPlay setEnabled true ButtonPause setEnabled true ButtonStepInto setEnabled true ButtonPlay setEnabled false ButtonPause setEnabled false ButtonStepInto setEnabled false public void addNextLevelAccess MemAccess ma if this getNextLevelRegistry this nextLevelDialog insertMemAccess ma imprime na interface qual o pr ximo acesso param ma O Ey public void setN acesso a mem ria extAccess MemAccess ma jTextFieldAddress setText ma getHexAddress toUpperCase jTextFiel jTextFiel public void setN int b3 this jLabelBits setText tag bl bits bits E EDS LdAccessType setText ma getAccessType ldAccessSize setText tma getSize extDecodedAddress long tag int index long offset int bl int index b2 bits this jLabelBinary setText this jTextFieldTag setColumns b1 this this this this this this this this this this jTextFieldBinario setColumns bl jTextFieldIndex setColumns b2 jTextFieldBinario2 setColumns b2 jTextFieldOffset setColumns b3 jTextFieldBinario3 setColumns b3 jTextFieldTag setText tag jTextFieldBinario setText bitFormat tag b1 jTextFieldIndex setText index jTextFieldBin
64. derSpeed jPanelToolbarControls add getJTextFieldSpeed return jPanelToolbarControls This method initializes jMenultemNewSim return javax swing JMenuItem E private JMenuItem getJMenuItemNewSim if jMenuItemNewSim null jMenuItemNewSim new JMenuItem jMenuItemNewSim setText New UnifiedCache Simulation jMenuItemNewSim addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e System out println actionPerformed TODO Auto generated Event stub actionPerformed UnifiedCacheDialog newSimDialog new UnifiedCacheDialog RunProgram this newSimDialog setVisible true return jMenuItemNewSim This method initializes jPanelStatus return javax swing JPanel private JPanel getJPanelStatus if jPanelStatus null jLabelStatus new JLabel jLabelStatus setText Estado do programa jPanelStatus new JPanel new BorderLayout jPanelStatus add jLabelStatus BorderLayout WEST return jPanelStatus This method initializes jPanelEstatisticas return javax swing JPanel xj private JPanel getJPanelEstatisticas if jPanelEstatisticas null jPanelEstatisticas new JPanel jPanelEstatisticas setLayout new BorderLayout jPanelEstatisticas add getJPanelEstatisticasControls BorderLayout NORTH jPanelEstatisticas add getJPanelNaoEsta
65. desc descricao this value value public String toString return desc 110 116 Arquitectura Avan ada de Computadores Simulador de Cache This method initializes jCheckBoxRegistry return javax swing JCheckBox A private JCheckBox getJCheckBoxRegistry if jCheckBoxRegistry null jCheckBoxRegistry new JCheckBox jCheckBoxRegistry setText Next Level Access Log jCheckBoxRegistry setSelected true return jCheckBoxRegistry jve decl index 0 visual constraint 10 10 111 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 17 WarningDialog Janela de dialogo simples usada para lan ar mensagens de alerta Esta janela bloqueia o acesso janela que a lan ou package cacheSim import java awt BorderLayout import java awt Color import java awt FlowLayout import java awt Frame import javax swing BorderFactory import javax swing JPanel import javax swing JDialog import javax swing JButton import javax swing JTextPane Janela de dialogo de uso geral Apenas serve de alerta para o utilizador Qauthor Manuel Y public class WarningDialog extends JDialog public static final long serialVersionUID 0 private JPanel jContentPane null private JPanel jPanel null private JButton jButton null private JTextPane jTextPaneMessage null This is the default constructor x
66. dirty blocks index dirty_bit blocks index clean false if tag blocks index tag 36 116 Arquitectura Avan ada de Computadores Simulador de Cache blocks index dirty bit false blocks index tag tag blocks index setAccessTime blocks index setCreationTime if dirty return 1 else return 0 retorna 1 caso o bloco escolhido estiver dirty ou 0 se estiver limpo private int fifoSubst long tag boolean dirty int index 0 encontra o bloco que esta ha mais tempo sem nenhum hit for int i 0 i this n blocks i if blocks index getFIFOindex i mais antigo index i ultimo bloco a ser acedido lastAccessedBlockIndex index dirty blocks index dirty_bit if tag blocks index tag blocks index dirty bit false gt blocks i getFIFOindex pR o blocks index tag tag blocks index clean false blocks index setAccessTime blocks index setCreationTime set fifo index if dirty return 1 else return 0 37 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 5 MainCanvas Esta classe representa a rea de desenho que vis vel na interface principal Tem uma vari vel com os par metros da simula o e desenha no ecr de acordo com o estado interno da lt classe O estado interno controlado pela thread de simula o representado pela classe SimulationThread
67. ectedFile getAbsolutePath SplitCacheDialog this jTextFieldTraceFile setText chooser getSelectedFile getAb solutePath ND return jButtonOpenFile This method initializes jPanell2 return javax swing JPanel xy private JPanel getJPanell2 if jPanell2 null jPanell2 new JPanel new FlowLayout FlowLayout RIGHT jPanell2 add getJCheckBoxNextLevelReg null jPanell2 add getJButtonCancel null jPanell2 add getJButtonOK null 91 116 Arquitectura Avan ada de Computadores Simulador de Cache return jPanell2 This method initializes jButtonCancel return javax swing JButton X private JButton getJButtonCancel if jButtonCancel null jButtonCancel new JButton jButtonCancel setText Cancel jButtonCancel setPreferredSize labelDim jButtonCancel addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e System out println simulationCancel TODO Auto generated Event stub actionPerformed SplitCacheDialog this setVisible false return jButtonCancel This method initializes jButtonOK return javax swing JButton x4 private JButton getJButtonOK if jButtonOK null jButtonOK new JButton jButtonOK setText OK jButtonOK setPreferredSize labelDim jButtonOK addActionListener new java awt event ActionListener public
68. ed params getSplitCache doMemAccess ma ap s fazer o acesso ve se houveram acessos ao pr ximo nivel de memoria MemAccess array params getSplitCache getDCache getNextLevelAccess if array null for int i 0 i array length i window addNextLevelAccess array i Jelse RK RR RE RR RR RE RR EE RR RR ERROR RE kk EE RX RE RX ARX RE RX 3 UNIFIED CACHE sp RK KKK IK RR RE RR RR RE RR RE RX RR IR XKX RX A if params isUnifiedCache window setNextDecodedAddress params getUnifiedCache getUCache getTag ma params getUnifiedCache getUCache get Index ma params getUnifiedCache getUCache getOffset ma params getUnifiedCache getUCache getTagBits params getUnifiedCache getUCache getIndexBits params getUnifiedCache getUCache getOffsetBits 81 116 Arquitectura Avan ada de Computadores Simulador de Cache params getSplitCache getAccessBlockIndex int scroll y params getUnifiedCache getSetBlockIndex ma window myCanvas getBlockByteDrawSize y window myCanvas getCachelPos y window myCanvas setBackground new Color 200 255 200 window myCanvas setBlockSelected window myCanvas getCachelPos x MainCanvas X IN D BLOCK scroll y 0 params getUnifiedCache getSet Index ma Point p window scrollPaneCanvas getScrollPosition Dimension d window scrollPaneCanvas getSize if s
69. ee 17 6 2 LES TE Ro o Ret E ne bet t ttes 18 6 2 1 AboutDialog itte re e ad e tus 19 6 2 2 BOCK iere ete etr diee UR 22 6 2 39 Cache iei o edu eR e Hs 24 O24 CacheSCL sedan ca dett A ete teclats 33 6 2 5 Main Canvas si e eee ee eh ete e Orbe ie ease 38 6 2 0 MEMA CCE SSos Ud HEU He ER UH S ede HS d EI Een 4 6 27 MemAccessFile eerie Ee ON E epe E PA aes 50 02 8 Ks xT ated ue Pu re b ce ip p E oe lite e EE HERE es 52 6 2 9 NextLevelAccessDialog eeeeeeeeeseeeeeeeenennen ene niak iE 53 6 2 10 RunPtrogram nnde ode ibrus 58 6 24 SummPar ms nee edt eee e eee ot e aera 76 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 12 6 2 13 6 2 14 6 2 15 6 2 16 6 2 17 Simulation Freak ini eret ed eet ipee uas TI SplitCache ei er re eese ede ie D ive tp ete Tee eee seco 85 SplitCacheDuialog 2 io erat dp die ree eite cec 88 UnthiedCache oen eee et tiere 101 UnifiedCacheDialog idu oc OO Ere 103 Warmmgbrial g 5 etie eee e 112 II Arquitectura Avan ada de Computadores Simulador de Cache 1 Introdu o Este trabalho foi realizado no mbito da disciplina de Arquitectura Avan ada de Computadores do 5 ano da LEIC ano lectivo de 2005 2006 Consistiu em desenvolver um simulador de cache gen rico Entenda se por cache como um n vel de mem ria presente na arquitectura de qualquer computador moderno parte se do pressuposto que o leitor compreende minimamente o fun
70. eldIAccess setText 0 jTextFieldIAccess setEditable false jTextFieldIAccess setBackground Color WHITE return jTextFieldIAccess This method initializes jPanelNaoEstatisticas return javax swing JPanel T private JPanel getJPanelNaoEstatisticas if jPanelNaoEstatisticas null jLabell5 new JLabel jLabell5 setText Data Writes jLabell5 setHorizontalAlignment JLabel RIGHT jLabell4 new JLabel jLabell4 setText Data Reads jLabell4 setHorizontalAlignment JLabel RIGHT jLabell3 new JLabel jLabell3 setText Instructions 70 116 Arquitectura Avan ada de Computadores Simulador de Cache return jPanelNaoEstatisticas This method initializes jTextFieldDRAccess jLabell3 setHorizontalAlignment JLabel RIGHT jLabell2 new JLabel jLabell2 setText Acessos jLabelll new JLabel jLabelll setText jPanelNaoEstatisticas new JPanel jPanelNaoEstatisticas setLayout new GridLayout 5 2 5 5 jPanelNaoEstatisticas add jLabelll null jPanelNaoEstatisticas add jLabell2 null jPanelNaoEstatisticas add jLabell3 null jPanelNaoEstatisticas add getJTextFieldIAccess null jPanelNaoEstatisticas add jLabell4 null jPanelNaoEstatisticas add getJTextFieldDRAccess null jPanelNaoEstatisticas add jLabell5 null jPanelNaoEstatisticas add getJTextFieldDWAccess null return javax swing JTextField ST p
71. ente dirty x public int doDataWriteAccess long tag int substPolicy int writePolicy se a politica de escrita for write through no allocate n o altera nada if writePolicy Cache WR THROUGH NO ALLOCATE return 0 n o conta como uma cache miss o resto s executado se for um write back verifica se os dados est o num dos blocos for int i 0 i lt n blocks i if blocks i hasTag tag blocks i setCreationTime n o pk no caso de hit blocks i setAccessTime hit tempo para o LRU blocks i dirty bit true this lastAccessedBlockIndex i return 0 T verifica se existem blocos livres neste caso existem falhas porque tem q ir buscar o resto do bloco for int i 0 i lt n blocks i verifica se existe algum bloco limpo if blocks i isClean blocks i tag tag blocks i clean false blocks i dirty_bit true blocks i setAccessTime blocks i setCreationTime FIFO index this lastAccessedBlockIndex i return 1 return 0 se for para eliminar falhas compuls rias 34 116 Arquitectura Avan ada de Computadores Simulador de Cache return 1 se contar com tudo int ret CUIDADO tem que meter o dirty_bit a true politica de substitui o if writePolicy Cache WR BACK ALLOCATE switch substPolicy case Cache S RANDOM ret randomSubst tag blocks lastAccessedBlockIndex dirty bit true return l ret case Cache S LRU
72. ente um objecto do tipo Cache optou se por esta solu o para normalizar o programa package cacheSim Representa uma cache unificada cache de dado cache de instru es tudo na mesma cache Esta classe execut vel para poder correr simula es pesadas author Manuel Hef public class UnifiedCache Cache uCache private MemAccess lastMemAccess public UnifiedCache Cache uCache throws Exception if uCache isInstrCache throw new Exception unified cache can t be an instruction cache this uCache uCache public MemAccess getLastMemAccess return this lastMemAccess public long getNumAccess return uCache getNumAccess public long getNumHits return uCache getNumHits public long getNumMisses return uCache getNumMisses public long getNumWriteThroughs return uCache getNumWriteThroughs public long getNumWriteBacks return uCache getNumWriteBacks public long getNumIAccess return uCache getNumIAccess public long getNumDRAccess return uCache getNumDRAccess public long getNumDWAccess return uCache getNumDWAccess public long getNumNextLevelAccess return uCache getNumNextLevelAccess public Cache getUCache return uCache public int getLastAccessBlockIndex return uCache getLastAccessBlockIndex 101 116 Arquitectura Avan ada de Computadores Simulador de Cache
73. es this return void private void initialize this setSize 356 331 this setContentPane getJContentPane this setTitle About This method initializes jContentPane return javax swing JPanel private JPanel getJContentPane if jContentPane null jContentPane new JPanel jContentPane setLayout new BorderLayout jContentPane add getJPanelCenter java awt BorderLayout SOUTH jContentPane add getJPanell java awt BorderLayout NORTH jContentPane add getJScrollPane java awt BorderLayout CENTER return jContentPane 19 116 Arquitectura Avan ada de Computadores Simulador de Cache This method initializes jPanelCenter return javax swing JPanel xf private JPanel getJPanelCenter if jPanelCenter null jPanelCenter new JPanel jPanelCenter setBackground new java awt Color 204 51 0 jPanelCenter add getJButtonOk null return jPanelCenter This method initializes jButtonOk return javax swing JButton y private JButton getJButtonOk if jButtonOk null jButtonOk new JButton jButtonOk setText OK jButtonOk addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e AboutDialog this setVisible false return jButtonOk This method initializes jPanell return javax swing JPanel m private JPanel get
74. ex pk se trata do index nao pode ser inserido c digo aqui porque ainda nada foi inicializado i 1 if i gt 0 MemAccess lma sim getSplitCache getLastMemAccess int offset int size lma getSize if lma isInstructionAccess offset int sim getSplitCache getICache getOffset lma else offset int sim getSplitCache getDCache getOffset lma cache de instru es if sim getSplitCache getLastUsedCache g setColor Color ORANGE g fillRect cl x X IND BLOCK 1 cl y bb y i bsizel x 1 bb y for int j 0 j size j t g setColor Color RED g fillRect cl x X IND BLOCK offset bb x j bb x cl y bb y i bb x bb y g setColor Color BLACK g drawRect cl x X IND BLOCK offset bb x j bb x cl y bb y i bb x bb y 44 116 Arquitectura Avan ada de Computadores Simulador de Cache g setColor Color BLACK g drawRect cl x 3 cl y bb y i bsizel x X IND BLOCK 3 bb y else cache de dados g setColor Color ORANGE g fillRect c2 x X IND BLOCK 1 c2 y bb y i bsize2 x 1 bb y for int j 0 j size j t g setColor Color RED g fillRect c2 x X IND BLOCK offset bb x j bb x c2 y bb y i bb x bb y g setColor Color BLACK g drawRect c2 x X IND BLOCK offset bb x j bb x c2 y bb y i bb x bb y g setColor Color BLACK g drawRect c2 x
75. ext paint if this playmode amp amp this sleepTime lt SILENT MODE amp amp this pause try if maf hasMore window resetStatistcsBackColor 71 116 Arquitectura Avan ada de Computadores Simulador de Cache MemAccess ma ma maf getNext window setNextAccess ma if params isSplitCache if ma isInstructionAccess window setNextDecodedAddress params getSplitCache getICache getTag ma params getSplitCache getICache getIndex ma params getSplitCache getICache getOffset ma params getSplitCache getICache getTagBits params getSplitCache getICache getIndexBits params getSplitCache getICache getOffsetBits Jelsef window setNextDecodedAddress params getSplitCache getDCache getTag ma params getSplitCache getDCache getIndex ma params getSplitCache getDCache getOffset ma params getSplitCache getDCache getTagBits params getSplitCache getDCache getIndexBits params getSplitCache getDCache getOffsetBits params getSplitCache doMemAccess ma regista os acessos ao nivel seguinte de mem ria if ma isInstructionAccess MemAccess array params getSplitCache getICache getNextLevelAccess if array null for int i 0 i array length i window addNextLevelAccess array i ERRADO selse MemAccess array params getSpli
76. extArea getText ma toString n array add ma if this isVisible int index array size 100 if index lt 0 index 0 55 116 Arquitectura Avan ada de Computadores Simulador de Cache ListIterator lt MemAccess gt itr array listIterator index String s new String while itr hasNext S An itr next toString jTextArea setText s this scrollPane setScrollPosition 0 this jTextArea getSize height 50 MemAccess mas new MemAccess this maArray length 1 for int i 0 i this maArray length i mas i this maArray i mas this maArray length ma maArray mas this jList setSelectedIndex maArray length 1 this jList setAutoscrolls true This method initializes jTextArea return javax swing JTextArea x private JTextArea getJTextArea if jTextArea null jTextArea new JTextArea jTextArea setBounds new java awt Rectangle 5 101 10 16 jTextArea setFont new Font Courier New Font PLAIN 12 return jTextArea This method initializes scrollPane return java awt ScrollPane E private ScrollPane getScrollPane if scrollPane null scrollPane new ScrollPane ScrollPane add getJTextArea null return scrollPane This method initializes jPanel return javax swing JPanel E private JPanel getJPanel if jPanel null jLabell
77. f RK KKK IK KK IK RR RE RR EE RARA f if params isSplitCache if ma isInstructionAccess window setNextDecodedAddress params getSplitCache getICache getTag ma params getSplitCache getICache getIndex ma params getSplitCache getICache getOffset ma 79 116 Arquitectura Avan ada de Computadores Simulador de Cache params getSplitCache getICache getTagBits params getSplitCache getICache getIndexBits params getSplitCache getICache getOffsetBits i else window setNextDecodedAddress params getSplitCache getDCache getTag ma params getSplitCache getDCache getIndex ma params getSplitCache getDCache getOffset ma params getSplitCache getDCache getTagBits params getSplitCache getDCache getIndexBits params getSplitCache getDCache getOffsetBits if ma isInstructionAccess params getSplitCache getAccessBlockIndex int scroll y params getSplitCache getSetBlockIndex ma window myCanvas getBlockByteDrawSize y window myCanvas getCachelPos y window myCanvas setBackground new Color 200 255 200 window myCanvas setBlockSelected window myCanvas getCachelPos x MainCanvas X IN D BLOCK scroll y 0 params getSplitCache getSetIndex ma Point p window scrollPaneCanvas getScrollPosition Dimension d window scrollPaneCanvas getSize if scroll y p y amp amp Sc
78. f public WarningDialog JDialog frame String title String message super frame true initialize this setTitle title this setSize 300 200 this setLocationRelativeTo null this setResizable false this jTextPaneMessage setText message public WarningDialog Frame frame String title String message super frame true initialize this setTitle title this setSize 300 200 this setLocationRelativeTo null this setResizable false this jTextPaneMessage setText message This method initializes this return void private void initialize this setSize 300 200 this setContentPane getJContentPane This method initializes jContentPane return javax swing JPanel 112 116 Arquitectura Avan ada de Computadores Simulador de Cache private JPanel getJContentPane if jContentPane null jContentPane new JPanel jContentPane setLayout new BorderLayout jContentPane add getJPanel java awt BorderLayout SOUTH jContentPane setBorder BorderFactory createEmptyBorder 10 10 10 10 jContentPane add getJTextPaneMessage java awt BorderLayout CENTER return jContentPane This method initializes jPanel return javax swing JPanel 7 private JPanel getJPanel if jPanel null jPanel new JPanel new FlowLayout FlowLayout RIGHT jPanel add getJButton null return jPanel
79. faz 2 acesso a mem ria um para escrever o bloco e outro para escrever return 1 randomSubst tag case Cache S LRU return l lruSubst tag case Cache S FIFO return 1 fifoSubst tag default System out println CacheSet doDataReadAccess N o devia acontecer isto return 9999999 public int getLastAccessedBlockIndex return lastAccessedBlockIndex public Block getLastAccessedBlock return this blocks this lastAccessedBlockIndex retorna 1 caso o bloco escolhido estiver dirty ou 0 se estiver limpo private int randomSubst long tag boolean dirty int b int Math random n_blocks ultimo bloco a ser acedido lastAccessedBlockIndex b dirty blocks b dirty_bit System out println Random b blocks b clean false so coloca o dirty a false se a tag for igual if tag blocks b tag blocks b dirty bit false blocks b tag tag blocks b setAccessTime blocks b setCreationTime if dirty return 1 else return 0 retorna 1 caso o bloco escolhido estiver dirty ou 0 se estiver limpo private int lruSubst long tag boolean dirty int index 0 encontra o bloco que esta ha mais tempo sem nenhum hit for int i 0 i this n blocks i if blocks index getLastAccessTime gt blocks i getLastAccessTime pk o i mais antigo index i ultimo bloco a ser acedido lastAccessedBlockIndex index
80. g JMenu x4 private JMenu getFileMenu if fileMenu null fileMenu new JMenu fileMenu setText File fileMenu add getJMenuItemNewSim fileMenu add getJMenuItemNewSim2 fileMenu add getExitMenuItem return fileMenu This method initializes jMenu return javax swing JMenu private JMenu getHelpMenu if helpMenu null helpMenu new JMenu helpMenu setText Help helpMenu add getAboutMenuItem return helpMenu This method initializes jMenuItem return javax swing JMenuItem x private JMenuItem getExitMenuItem if exitMenuItem null exitMenuItem new JMenuItem exitMenuItem setText Exit exitMenuItem addActionListener new ActionListener public void actionPerformed ActionEvent e System exit 0 return exitMenuItem This method initializes jMenuItem return javax swing JMenuItem x4 private JMenuItem getAboutMenuItem if aboutMenuItem null aboutMenuItem new JMenuItem aboutMenuItem setText About aboutMenuItem addActionListener new ActionListener public void actionPerformed ActionEvent e new AboutDialog RunProgram this About true show new AboutDialog RunProgram this setVisible true Dm return aboutMenuItem 75 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 11 SimParams Esta classe contem os par
81. ghs return this n_write_throughs public long getNumWriteBacks return this n_write_backs public long getNumIAccess return this n_instr_access public long getNumDRAccess return this n_dataread_access 30 116 Arquitectura Avan ada de Computadores Simulador de Cache pub pub publ publ publ publ publ publ publ lic iq lic lic TE lic ic io ic public public public long getNumDWAccess return this n_datawrite_access long getNumAccess return this n_access long getNumHits return this n_hits long getNumMisses return this n_misses String replacePolicyToString switch this substituicao case Cache S_FIFO return FIFO case Cache S_RANDOM return RANDOM case Cache S_LRU return LRU default return direct mapping String writePolicyToString switch this escrita case Cache WR_BACK_ALLOCATE return write back write no allocate case Cache WR_THROUGH_NO_ALLOCATE return write through write allocate default return no write policy int getNumBlocks return this blocks int getNumSets return this sets int getBlockSize return this block_size Block getBlock int b int index b this associatividade int bindex b this associatividade return cache index getBlock bindex boolean isInstrCache
82. hooser getSelectedFile get AbsolutePath Dj return jButtonOpenFile This method initializes jPanell return javax swing JPanel XI private JPanel getJPanell if jPanell null jPanell new JPanel new GridLayout 5 1 5 5 jPanell setBorder BorderFactory createTitledBorder BorderFactory createLineBorder Color BLACK 1 Unified Cache jPanell add getJPanel3 null jPanell add getJPanel4 null jPanell add getJPanel2 null jPanell add getJPanel5 null jPanell add getJPanell0 null return jPanell This method initializes jPanel2 return javax swing JPanel x private JPanel getJPanel2 if jPanel2 null jLabel6 new JLabel jLabel6 setText bytes jPanel2 new JPanel new FlowLayout FlowLayout LEFT jPanel2 add getJPanel8 null jPanel2 add getJTextFieldBlockSize null jPanel2 add jLabel6 null return jPanel2 This method initializes jTextField return javax swing JTextField x private JTextField getJTextFieldBlockSize if jTextFieldBlockSize null jTextFieldBlockSize new JTextField jTextFieldBlockSize setColumns 10 jTextFieldBlockSize setText 64 return jTextFieldBlockSize This method initializes jPanel3 Qreturn javax swing JPanel 7 private JPanel getJPanel3 if jPanel3 null jLabel5 new JLabel jLabel5 setText k
83. ias 5 1 Bibliografia Acetatos das aulas te ricas de Arquitectura Avan ada de Computadores Jo o Canas Ferreira Ano lectivo 2005 2006 5 2 Software Plataforma de desenvolvimento Eclipse SDK v3 1 1 Sun Microsystems Java TM Runtime Environment Standard Edition 1 5 0 b64 12 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 Ap ndices 6 1 Manual do utilizador 6 1 1 Escolher a simula o Em primeiro lugar necess rio escolher a simula o que se pretende fazer tanto pode ser uma simula o para um cache unificada como para uma cache separada Antes de criar a simula o os controles est o desactivados escolhe o tipo de simula o aax fi my Cache Simulator New UnifiedCache Simulation New SplitCache Simulation next step M00 Exit Address Access Type Access Size Binary Address Decimal Address tag index offset Estatisticas Acessos 0 ge dor dada Pn 13 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 1 2 Especificar a cache Despois de escolher o tipo de simula o o utilizador preenche as caracter sticas da cache e diz qual o ficheiro de acessos necess rio simula o selecciona o ficheiro de acessos New Simulation Trace File caracteristicas da cache de i kilobytes dados loitas associativity number of blocks per set block size 64 by
84. icasControls add getJTextFieldCacheHits null jPanelEstatisticasControls add jLabel6 null jPanelEstatisticasControls add getJTextFieldCacheMiss null jPanelEstatisticasControls add jLabel9 null jPanelEstatisticasControls add getJTextFieldWriteThroughs null jPanelEstatisticasControls add jLabel8 null jPanelEstatisticasControls add getJTextFieldWriteBacks null jPanelEstatisticasControls add jLabell0 null jPanelEstatisticasControls add getJTextFieldNextLevel null return jPanelEstatisticasControls This method initializes jTextFieldAcessos return javax swing JTextField Rj private JTextField getJTextFieldAcessos if jTextFieldAcessos nu jTextFieldAcessos jTextFieldAcessos jTextFieldAcessos jTextFieldAcessos jTextFieldAcessos return jTextFieldAcessos 11 4 new JTextField setColumns 8 setText 0 setEditable false setBackground Color WHITE This method initializes jTextFieldCacheHits return javax swing JTextField private JTextField getJTextFieldCacheHits if jTextFieldCacheHits jTextFieldCacheHits jTextFieldCacheHits jTextFieldCacheHits jTextFieldCacheHits return jTextFieldCacheHits null new JTextField setText 0 setEditable false setBackground Color WHITE This method initializes jTextFieldCacheMiss 66 116 Arquitectura Avan ada de Comput
85. ilobytes jPanel3 new JPanel new FlowLayout FlowLayout LEFT jPanel3 add getJPanel6 null jPanel3 add getJTextFieldSize null jPanel3 add jLabel5 null 106 116 Arquitectura Avan ada de Computadores Simulador de Cache return jPanel3 This method initializes jTextFieldl return javax swing JTextField RA private JTextField getJTextFieldSize if jTextFieldSize null jTextFieldSize new JTextField jTextFieldSize setColumns 10 jTextFieldSize setText 32 return jTextFieldSize This method initializes jPanel4 return javax swing JPanel sj private JPanel getJPanel4 if jPanel4 null jLabel4 new JLabel jLabel4 setText number of blocks per set jPanel4 new JPanel new FlowLayout FlowLayout LEFT jPanel4 add getJPanel7 null jPanel4 add getJTextFieldAssociatividade null jPanel4 add jLabel4 null return jPanel4 This method initializes jTextField2 return javax swing JTextField XT private JTextField getJTextFieldAssociatividade if jTextFieldAssociatividade null jTextFieldAssociatividade new JTextField jTextFieldAssociatividade setColumns 10 jTextFieldAssociatividade setText 2 return jTextFieldAssociatividade This method initializes jPanel5 return javax swing JPanel 7 private JPanel getJPanel5 if jPanel5 null jPanel5 new J
86. initializes jPanel6 return javax swing JPanel XI private JPanel getJPanel6 if jPanel6 null jLabel6 new JLabel jLabel6 setText bytes jPanel6 new JPanel new FlowLayout FlowLayout LEFT 94 116 Simulador de Cache Arquitectura Avan ada de Computadores Simulador de Cache jPanel6 add getJPanel7 null jPanel6 add getJTextField2 null jPanel6 add jLabel6 null return jPanel6 This method initializes jPanel7 return javax swing JPanel REA private JPanel getJPanel7 if jPanel7 null jLabel5 new JLabel jLabel5 setText block size jPanel7 new JPanel jPanel7 setPreferredSize labelDim jPanel7 add jLabel5 null return jPanel7 This method initializes jTextField2 return javax swing JTextField sy private JTextField getJTextField2 if jTextField2 null jTextField2 new JTextField jTextField2 setColumns 10 jTextField2 setText 64 return jTextField2 This method initializes jPanel8 return javax swing JPanel private JPanel getJPanel8 if jPanel8 null jPanel8 new JPanel new FlowLayout FlowLayout LEFT jPanel8 add getJPanel9 null jPanel8 add getJComboBoxReplacePolicy null return jPanel8 This method initializes jPanel9 return javax swing JPanel TUA private JPanel getJPanel9 if jPanel9 null jLabel7 new JLabel
87. ionEvent e System out println simulationOK TODO Auto generated Event stub actionPerformed mainFrame setReadyStatus true UnifiedCacheDialog this setVisible false try int u_kb Integer parselnt jTextFieldSize getText int u_sets Integer parseInt jTextFieldAssociatividade getText int u block Integer parseInt jTextFieldBlockSize getText int u sub MyItem jComboBoxReplacePolicy getSelectedItem value int u wr MyItem jComboBoxWritePolicy getSelectedItem value Cache uCache new Cache u kb u block u sets u sub u wr true UnifiedCache unifiedCache new UnifiedCache uCache SimParams simParams new SimParams if jTextFieldTraceFile getText compareTo 0 WarningDialog wd new WarningDialog UnifiedCacheDialog this Warning nYou have to select a compatible trace file n nUse the button to find it wd setVisible true else mainFrame setNextLevelRegistry jCheckBoxRegistry isSelected mainFrame setupSimThread new SimParams unifiedCache jTextFieldTraceFile getText mainFrame setReadyStatus true UnifiedCacheDialog this setVisible false T catch Exception exc WarningDialog wd new WarningDialog UnifiedCacheDialog this Erro exc toString wd setVisible true return jButtonOR private class MyItem public int value public String desc public MyItem String descricao int value
88. kage cacheSim import java lang Exception Representa uma cache de leitura escrita Tem um um array de CacheSet que simula os v rios conjuntos da cache Tem fun es para fazer acessos a mem ria e outros para buscar informa o da cache author Manuel public class Cache Politica de substitui o FIFO ur public static final int S FIFO 100 Politica de substitui o RANDOM S public static final int S RANDOM 101 Politica de substitui o ASSOCIATIVIDADE COMPLETA public static final int S_LRU 102 Politica de escrita write through write allocate 5 public static final int WR THROUGH NO ALLOCATE 0 Politica de escrita write back write no allocate pd public static final int WR BACK ALLOCATE 1 N o existe politica de escrita cache de instru es iA public static final int WR INSTR CACHE 2 public static final int DIRECT MAPPING 0 propriedades da cache private int size private int blocks private int block size private int block size bits private int index size bits private int associatividade private int substituicao private int escrita politica de escrita private int sets 24 116 Arquitectura Avan ada de Computadores Simulador de Cache protected CacheSet cache estatisticas private long n hits private long n misses private long n access private long n instr access priva
89. l null abel jLabell2 null abel jLabell3 null extField jTextFieldIAcc abel jLabell4 null extField jTextFieldDRAc null null E 1 null ols null null 1 1 null Controls null sos null eHits null eMiss null s null i15 d null 1 ls null ess null SsType null ssSize null 2 null trols null velAccess null eBacks null eThroughs null Level null cas null ess null cess null 59 116 Arquitectura Avan ada de Computadores Simulador de Cache b2 offset private private private private private private private private private JI private private JI JLabel 5 JPanel 5 JLabel 5 JPanel 5 JPanel 5 private private private JLabel 5 JPanel 5 JLabel 5 if b t 3 j j Jelsel 7 7 7 JTextField jTextFieldDWAccess JTextField 5 JTextField extField JTextField extField private JTextField jTextFieldOffset public boolean getNextLevelRegistry return this nextLevelRegistry public void setReadyStatus boolean b this myCanvas repaint Labell5 null i null PanelAccessDecoded null LabelDecimal null jTextFieldTag null Panel null Panell null extFieldBinario TextFieldBinario2 null extFieldBinario3 null extFieldIndex null null j1 null 31 31 31 LabelBinary PanelDecode
90. lVersionUID 0 public CacheFormatException String s super s 32 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 4 CacheSet Esta classe representa um conjunto da cache a cache constitu da por um array destes objectos Por sua vez esta classe tem um array de blocos Nesta classe est o os algoritmos de substitui o e escrita esta era a op o mais l gica visto esses algoritmos escolhem o bloco para substituir escrever dentro do conjunto que representado por esta classe package cacheSim Representa um conjunto da cache Aqui decide se qual o bloco a substituir etc Tem um array de Blocks que representa os blocos deste conjunto author Manuel public class CacheSet private int n blocks private Block blocks private int block size podia contabilizar as falhas compulsorias private boolean falhas compulsorias flag que indica o index do ultimo bloco que foi acedido serve pra efeitos de desenho etc private int lastAccessedBlockIndex public CacheSet int n blocks int block size this lastAccessedBlockIndex 1 this n blocks n blocks this block size block size blocks new Block n blocks for int i 0 i lt n blocks i blocks il new Block block size public int getNBlocks return n_blocks T public int getBlockSize return block size public Block getBlock int index
91. lay if jButtonPlay null jButtonPlay new JButton createImageIcon play gif teste jButtonPlay setEnabled false jButtonPlay setText play jButtonPlay addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e System out println play TODO Auto generated Event stub actionPerformed garante que s cria uma thread if animationThread null animationThread new SimulationThread RunProgram this animationThread start else animationThread setPause false animationThread setPlayMode true 63 116 Arquitectura Avan ada de Computadores Simulador de Cache return jButtonPlay protected static Imagelcon createImageIcon String path String description java net URL imgURL RunProgram class getResource path if imgURL null return new Imagelcon imgURL description else System err println Couldn t find file path return null This method initializes jButtonPause return javax swing JButton 7 private JButton getJButtonPause if jButtonPause null jButtonPause new JButton jButtonPause new JButton createImageIcon pause gif teste jButtonPause setEnabled false jButtonPause setText pause jButtonPause addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e System out println
92. lor WHITE jTextFieldTag setFont new Font Courier New Font PLAIN 12 return jTextFieldTag This method initializes jPanel return javax swing JPanel X private JPanel getJPanel2 if jPanel null jLabelDecimal new JLabel jLabelDecimal setText Decimal Address jLabelDecimal setFont new Font Courier New Font PLAIN 12 jPanel new JPanel new FlowLayout FlowLayout LEFT jPanel setBorder BorderFactory createTitledBorder BorderFactory createLineBorde r Color LIGHT GRAY 0 Address decimal jPanel add getJTextFieldTag null jPanel add getJTextFieldIndex null jPanel add getJTextFieldOffset null jPanel add jLabelDecimal null return jPanel This method initializes jPanell return javax swing JPanel x private JPanel getJPanell if jPanell null jLabelBinary new JLabel jLabelBinary setText Binary Address jLabelBinary setFont new Font Courier New Font PLAIN 12 jPanell new JPanel new FlowLayout FlowLayout LEFT jPanell add getJTextFieldBinario null jPanell add getJTextFieldBinario2 null jPanell setBorder BorderFactory createTitledBorder BorderFactory createLineBord er Color LIGHT GRAY O Address binary jPanell add getJTextFieldBinario3 null jPanell add jLabelBinary null return jPanell This method initializes jTextFieldBinario return jav
93. lse window setStatusMessage Paused adormece por um bocado try catch private void showStatistcs if params isSplitCache SplitCache x long acessos long next level wr back long i access x getNumMisses x getNumWriteThroughs x getNumNextLevelAccess if params isUnifiedCache UnifiedCache x x getNumMisses x getNumWriteThroughs x getNumNextLevelAccess public void setPause boolean b this pause b this playmode if pause false else window setStatusMessage Running public void setStepInto boolean b this pause this playmode false this stepinto b if this stepinto true window setStatusMessage Step Into Enabled public void setSpeed int sleep this sleepTime sleep window setStatistcs x getNumAccess x getNumIAccess x getNumIAccess window setStatusMessage Paused Thread sleep sleepTime InterruptedException ex params getSplitCache long hits long misses long wr throughs long long dr access long dw access x getNumHits x getNumWriteBacks x getNumDRAccess x getNumDWAccess params getUnifiedCache window setStatistcs x getNumAccess x getNumHits x getNumWriteBacks x getNumDRAccess x getNumDWAccess T H ie if this sleepTime lt SILENT MODE window setStatusMessage Silent Mode public
94. method initializes jTextFieldSpeed return javax swing JTextField EZ private JTextField getJTextFieldSpeed if jTextFieldSpeed null jTextFieldSpeed new JTextField jTextFieldSpeed setEditable false jTextFieldSpeed setColumns 4 jTextFieldSpeed setText RunProgram START_SLEEP return jTextFieldSpeed 67 116 Arquitectura Avan ada de Computadores Simulador de Cache This method initializes jPanelAccess return javax swing JPanel REA private JPanel getJPanelAccess if jPanelAccess null jPanelAccess new JPanel new GridLayout 1 2 5 5 jPanelAccess add getJPanelAccessControls return jPanelAccess This method initializes jPanelAccessControls return javax swing JPanel EA private JPanel getJPanelAccessControls if jPanelAccessControls null Label7 new JLabel Label7 setText Access Size Labell new JLabel Labell setText Access Type Label new JLabel Label setText Address PanelAccessControls new JPanel PanelAccessControls add jLabel null PanelAccessControls add getJTextFieldAddress null PanelAccessControls add jLabell null PanelAccessControls add getJTextFieldAccessType null uU PanelAccessControls add jLabel7 null PanelAccessControls add getJTextFieldAccessSize null return jPanelAccessControls This method initializes jTextFieldAddress
95. mport javax swing JCheckBox Representa a janela de dialogo onde o utilizador insere os dados da SplitCache e o ficheiro com os acessos Gauthor Manuel xo F F X public class SplitCacheDialog extends JDialog public static final long serialVersionUID 0 private JPanel jContentPane null private JPanel jPanelCenter null private JPanel jPanel null private JLabel jLabel null private JTextField jTextFieldTraceFile null private JButton jButtonOpenFile null private final Dimension labelDim new Dimension 100 25 private JPanel jPanell2 null private JButton jButtonCancel null private JButton jButtonOK null private RunProgram mainFrame private JPanel jPanell3 null private JPanel jPanell null private JPanel jPanel2 null private JPanel jPanel3 null private JLabel jLabell null private JTextField jTextField null private JLabel jLabel2 null private JPanel jPanel4 null 88 116 Arquitectura Avan ada de Computadores Simulador de Cache private private private private private private private private private private private private private private private private private private private private private private private private private private private private private private private private private private private private
96. new JLabel jLabell setText size jPanel3 new JPanel 93 116 Arquitectura Avan ada de Computadores jPanel3 setPreferredSize labelDim jPanel3 add jLabell null return jPanel3 This method initializes jTextField return javax swing JTextField 7 private JTextField getJTextField if jTextField null jTextField new JTextField jTextField setColumns 10 jTextField setText 16 return jTextField This method initializes jPanel4 return javax swing JPanel ST private JPanel getJPanel4 if jPanel4 null jLabel4 new JLabel jLabel4 setText number of blocks per set jPanel4 new JPanel new FlowLayout FlowLayout LEFT jPanel4 add getJPanel5 null jPanel4 add getJTextFieldl null jPanel4 add jLabel4 null return jPanel4 This method initializes jPanel5 return javax swing JPanel private JPanel getJPanel5 if jPanel5 null jLabel3 new JLabel jLabel3 setText associativity jPanel5 new JPanel jPanel5 setPreferredSize labelDim jPanel5 add jLabel3 null return jPanel5 This method initializes jTextFieldl return javax swing JTextField x private JTextField getJTextFieldi if jTextFieldl null jTextFieldl new JTextField jTextFieldl setColumns 10 jTextFieldl setText 2 return jTextFieldl This method
97. objecto tem refer ncia aos par metros da simula o SimParams e a partir disso consegue buscar os dados necess rios sua renderiza o 2 5 Testes e valida o Nesta sec o apresenta se alguns resultados com o intuito de comprovar o funcionamento correcto do programa 2 5 1 Coer ncia dos dados Os primeiros testes realizados s o da coer ncia dos dados de esperar que com o aumento da cache a taxa de falhas diminua preciso ter cuidado com estes testes porque com o aumento da cache ocorrem mais falhas compuls rias como o ficheiro de acessos relativamente pequeno conv m evitar este erro utilizando se valores pequenos para o tamanho da cache 1 a 8 KB s o razo veis Estat sticas para os primeiros 10000 acessos tamanho do bloco 64bytes associatividade 2 pol tica de substitui o LRU e pol tica de escrita write back Tamanho KB misses next level hits 1 2 4204 5236 5796 Split Cache 2 2 3022 4879 6078 4 2 3797 4719 6203 2 4171 5169 5829 UnifiedCache 4 3032 4879 6068 8 3760 4679 6240 Como se pode ver nesta tabela os resultados apresentados nos testes s o coerentes Conforme se vai aumentando a capacidade da cache a taxa de falhas reduz razoavelmente apesar de n o se notar grandes melhorias Este fen meno exlicado pelo facto que existe uma 7 116 Arquitectura Avan ada de Computadores Simulador de Cache atenuante essa atenuante s o as
98. og wd new WarningDialog SplitCacheDialog this Erro exc toString wd setVisible true o return jButtonOK This method initializes jPanell3 return javax swing JPanel Ey private JPanel getJPanell3 if jPanell13 null jPanell13 new JPanel new BorderLayout jPanell3 add getJPanell BorderLayout NORTH jPanell3 add getJPanell4 java awt BorderLayout SOUTH return jPanell3 This method initializes jPanell return javax swing JPanel private JPanel getJPanell if jPanell null jPanell new JPanel new GridLayout 5 1 5 5 jPanell setBorder BorderFactory createTitledBorder BorderFactory createLineBorder Color BLACK 1 Data Cache jPanell add getJPanel2 null jPanell add getJPanel4 null jPanell add getJPanel6 null jPanell add getJPanel8 null jPanell add getJPanell0 null return jPanell This method initializes jPanel2 return javax swing JPanel x4 private JPanel getJPanel2 if jPanel2 null jLabel2 new JLabel jLabel2 setText kilobytes jPanel2 new JPanel new FlowLayout FlowLayout LEFT jPanel2 add getJPanel3 null jPanel2 add getJTextField null jPanel2 add jLabel2 null return jPanel2 This method initializes jPanel3 return javax swing JPanel XI private JPanel getJPanel3 if jPanel3 null jLabell
99. omboBoxWritePolicy new JComboBox 1 jComboBoxWritePolicy addItem new MyItem write back write allocate Cache WR BACK ALLOCATE jComboBoxWritePolicy addItem new MyItem write through write no allocate Cache WR THROUGH NO ALLOCATE return jComboBoxWritePolicy This method initializes jPanell4 return javax swing JPanel 7 private JPanel getJPanell4 if jPanell4 null jPanell4 new JPanel new GridLayout 5 1 5 5 jPanell4 setBorder BorderFactory createTitledBorder BorderFactory createLineBorde r Color BLACK 1 Instruction Cache jPanell4 add getJPanell15 null jPanell4 add getJPanell7 null jPanell4 add getJPanell9 null jPanell4 add getJPanel21 null jPanell4 add getJPanel23 null return jPanell4 This method initializes jPanell5 96 116 Arquitectura Avan ada de Computadores Simulador de Cache return javax swing JPanel private JPanel getJPanell5 if jPanell5 null jLabell0 new JLabel jLabellO setText kilobytes jPanell5 new JPanel new FlowLayout FlowLayout LEFT jPanell5 add getJPanell6 null jPanel15 add getJTextField3 null jPanell5 add jLabell0O null return jPanell5 This method initializes jPanell6 Qreturn javax swing JPanel REA private JPanel getJPanell6 if jPanell6 null jLabel9 new JLabel jLabel9 setText
100. onverte strings para inteiros P private static int strToInt String s int i Integer valueOf s intValue return i Converte hexadecimais de 32 bits para um long exemplos F9 ou F9 xi private static long hexToLong String hex converte valores hexadecimais long 1 Long valueOf hex 16 return 1 public String toString return this hex toUpperCase this type this size Exemplo de como usar o MemAccess 20 public static void main String args 48 116 Arquitectura Avan ada de Computadores Simulador de Cache try MemAccess x new MemAccess 3fbfe480 R 8 MemAccess y new MemAccess 3fbfe480 R gts resultado esperado seria Address Type Size 1069540480 R 8 System out println x x System out println y y catch Exception e e printStackTrace public static class MemAccessFormatException extends Exception static final long serialVersionUID 0 public MemAccessFormatException String s super s 49 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 7 MemAccessFile Representa o ficheiro que cont m os acessos necess rios simula o Usa um BufferedReader para aceder aos ficheiros package cacheSim import java io Representa o ficheiro onde se vai buscar os acessos a mem ria Usa um BufferedReader para maior performance Tem fung es para buscar o proximo
101. orderLayout CENTER jContentPane add getJPanel java awt BorderLayout SOUTH return jContentPane This method initializes jPanelControls return javax swing JPanel wre private JPanel getJPanelControls if jPanelControls null jPanelControls new JPanel new FlowLayout FlowLayout LEFT jPanelControls add getJButtonHide null jPanelControls add getJButtonSave null return jPanelControls This method initializes jButtonHide return javax swing JButton private JButton getJButtonHide if jButtonHide null jButtonHide new JButton jButtonHide setText Hide jButtonHide addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e NextLevelAccessDialog this setVisible false o return jButtonHide This method initializes jButtonSave return javax swing JButton XZ private JButton getJButtonSave if jButtonSave null jButtonSave new JButton jButtonSave setText Save to file jButtonSave addActionListener new java awt event ActionListener public void actionPerformed java awt event ActionEvent e 54 116 Arquitectura Avan ada de Computadores Simulador de Cache JFileChooser chooser new JFileChooser System getProperty user dir chooser setDialogType JFileChooser SAVE DIALOG chooser setDialogTitle Save as Note s
102. ource for ExampleFileFilter can be found in FileChooserDemo under the demo jfc directory in the Java 2 SDR Standard Edition int returnVal chooser showSaveDialog NextLevelAccessDialog this if returnVal JFileChooser APPROVE OPTION System out println You chose to open this file chooser getSelectedFile getName System out println File chooser getSelectedFile getAbsolutePath File f chooser getSelectedFile if f exists new WarningDialog NextLevelAccessDialog this Erro Ficheiro f getName j existe escolha outro nome setVisible true else try saveToFile f catch Exception exc new WarningDialog NextLevelAccessDialog this Erro Problemas ao escrever para o ficheiro rf getName setVisible true if f delete System out println File deleted NextLevelAccessDialog this jTextFieldTraceFile setText chooser getSelectedFile getAbsolutePath ND return jButtonSave private void saveToFile File file throws IOException FileWriter fw new FileWriter file BufferedWriter bw new BufferedWriter fw ListIterator itr this array listIterator 0 while itr hasNext 11 bw write itr next n bw close fw close public void clearList this jTextArea setText this array new LinkedList lt MemAccess gt public void insertMemAccess MemAccess ma jTextArea setText jT
103. para a pol tica de substituig o FIFO public Block int block_size this dirty bit false this clean true this tag 0 this block size block size this lastAccess System nanoTime System currentTimeMillis this creationTime System nanoTime public boolean isDirty return dirty bit public long getFIFOindex return this creationTime public void setAccessTime this lastAccess System nanoTime public void setCreationTime this creationTime System nanoTime public long getLastAccessTime return this lastAccess public boolean isClean return clean 22 116 Arquitectura Avan ada de Computadores Simulador de Cache public int getBlockSize return this block_size public long getTag return this tag public boolean hasTag long tag if clean return false if this tag tag return true else return false 23 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 3 Cache Esta classe uma das mais importantes neste programa representa uma cache gen rica tanto pode ser usada para simular uma cache unicamente de instru es como uma cache de dados ou ambas Tem um array de conjuntos um array de objectos do tipo CacheSet esse array representa os v rios conjuntos que existem na cache Tem fun es para executar acessos a mem ria e outros para buscar informa es relativas cache pac
104. res Simulador de Cache System out println BlockSize bits this block size bits IndexSize bits index size bits executa um acesso a mem ria param ma Acessoa mem ria do tipo MemAcess throws CacheFormatException xj public void doMemAccess MemAccess memAccess throws CacheFormatException int ret 0 MemAccess ma memAccess getCopy servia para verficar se o bloco saia for int i 0 i ma getSize i ma incAddress verifica se uma cache de instru es e se for s pode ser usada para buscar instru es if escrita WR INSTR CACHE amp amp ma isInstructionAccess throw new CacheFormatException Instruction Cache Only else CUIDADOOO0000000000000000000000000000000000000000000000000000 if ma isDataReadAccess f ret doDataReadAccess ma else if ma isDataWriteAccess ret doDataWriteAccess ma else if ma isInstructionAccess ret doInstructionAccess ma else System out println NAO SEI QUAL O TIPODL Dib bite blob kars LE LLEI Legals contabiliza o numero de acessos de cada tipo this n access if ma isDataReadAccess this n dataread access if ret 0 this n hits if ret 1 this n_access_to_next_level this n misses if ret 2 his n write backs his n misses his n access to next levelt 2 1 pelo miss 1 pelo o CE ct write back else if ma isDataWriteAc
105. ret IlruSubst tag blocks lastAccessedBlockIndex dirty bit true return l ret case Cache S FIFO ret fifoSubst tag blocks lastAccessedBlockIndex dirty bit true return l ret default System out println CacheSet doDataReadAccess N o devia acontecer isto return 9999999 T Jelsel System out println CacheSet doDataWriteAccess N o deveria nunca chegar a istol return 599599 param tag param substPolicy return 0 tag igual 1 tag diferente n o dirty empty 2 tag diferente dirty iA public int doDataReadAccess long tag int substPolicy verifica se os dados est o num dos blocos for int i20 i lt n blocks i if blocks i hasTag tag blocks i setAccessTime hit tempo para o LRU this lastAccessedBlockIndex i return 0 T verifica se existem blocos livres pode contar ou n o falhas compulsorias for int i 0 i lt n blocks i verifica se existe algum bloco limpo if blocks i isClean blocks i tag tag blocks i clean false blocks i dirty bit false blocks i setAccessTime blocks i setCreationTime FIFO index this lastAccessedBlockIndex i return 1 return 0 se for para eliminar falhas compuls rias return 1 se contar com tudo politica de substitui o switch substPolicy 35 116 Arquitectura Avan ada de Computadores Simulador de Cache case Cache S RANDOM
106. rivate private private private private private private private private private private private private private private JMenu helpMenu null JMenultem exitMenultem JMenultem aboutMenultem JP JP JB JB JB JP anel jPanelToolbar nul anel jPanelLegenda nul utton jButtonPlay nul utton jButtonPause nul utton jButtonStepInto anel jPanelToolbarContr JMenuItem jMenuItemNewSim JP JL JP JP JL JL JT JL JL JT JL JT JT JP JP JL JT JL TE JL JT anel jPanelStatus nul abel jLabelStatus nul anel jPanelEstatisticas anel jPanelEstatisticas abel jLabel2 null abel jLabel3 null extField jTextFieldAces abel jLabel4 null abel jLabel5 null extField jTextFieldCach abel jLabel6 null extField jTextFieldCach public ScrollPane scrollPaneCanva private JSlider jSliderSpeed nu extField jTextFieldSpee anel jPanelAccess nul anel jPanelAccessContro abel jLabel null extField jTextFieldAddr abel jLabell null extField jTextFieldAcce abel jLabel7 null extField jTextFieldAcce JMenuItem jMenuItemNewSim JP JB JL JT JL JT JL JT JP JL JL JL JT JL JT anel jPanelSecundaryCon utton jButtonShowNextLe abel jLabel8 null extField jTextFieldWrit abel jLabel9 null extField jTextFieldWrit abel jLabellO0 null extField jTextFieldNext anel jPanelNaoEstatisti abel jLabell
107. rivate JTextField getJTextFieldDRAccess if jTextFieldDRAccess null jTextFieldDRAccess new JTextField jTextFieldDRAccess setText 0 jTextFieldDRAccess setEditable false jTextFieldDRAccess setBackground Color WHITE return jTextFieldDRAccess This method initializes jTextFieldDWAccess return javax swing JTextField w private JTextField getJTextFieldDWAccess if jTextFieldDWAccess null jTextFieldDWAccess new JTextField jTextFieldDWAccess setText 0 jTextFieldDWAccess setEditable false jTextFieldDWAccess setBackground Color WHITE return jTextFieldDWAccess This method initializes jPanelAccessDecoded Qreturn javax swing JPanel x4 private JPanel getJPanelAccessDecoded if jPanelAccessDecoded null jPanelAccessDecoded new JPanel new BorderLayout 11 jPanelAccessDecoded add getJPanell BorderLayout NORTH jPanelAccessDecoded add getJPanel2 BorderLayout CENTER jPanelAccessDecoded add getJPanelDecodedTop java awt BorderLayout SOUTH return jPanelAccessDecoded This method initializes jTextFieldTag return javax swing JTextField private JTextField getJTextFieldTag if jTextFieldTag null jTextFieldTag new JTextField jTextFieldTag setColumns 32 71 116 Arquitectura Avan ada de Computadores Simulador de Cache jTextFieldTag setEditable false jTextFieldTag setBackground Co
108. roll y p y d height window scrollPaneCanvas setScrollPosition 0 scroll y 100 window myCanvas repaint para a simula o at step into do Thread sleep sleepTime while this stepinto amp amp pause amp amp terminateThread this stepinto false window myCanvas removeBlockSelected params getSplitCache doMemAccess ma MemAccess array params getSplitCache getICache getNextLevelAccess if array null for int i 0 i lt array length itt window addNextLevelAccess array i Jelse params getSplitCache getAccessBlockIndex 80 116 Arquitectura Avan ada de Computadores Simulador de Cache int scroll y params getSplitCache getSetBlockIndex ma window myCanvas getBlockByteDrawSize y window myCanvas getCache2Pos y window myCanvas setBackground new Color 200 200 255 window myCanvas setBlockSelected window myCanvas getCache2Pos x MainCanvas X IN D BLOCK scroll y 1 params getSplitCache getSetIndex ma Point p window scrollPaneCanvas getScrollPosition Dimension d window scrollPaneCanvas getSize if scroll y gt p y amp amp Scroll y p y d height window scrollPaneCanvas setScrollPosition 0 scroll y 100 window myCanvas repaint do Thread sleep sleepTime while this stepinto amp amp pause amp amp terminateThread this stepinto false window myCanvas removeBlockSelect
109. s 69 116 Arquitectura Avan ada de Computadores Simulador de Cache This method initializes jTextFieldWriteBacks return javax swing JTextField REA private JTextField getJTextFieldWriteBacks if jTextFieldWriteBacks null jTextFieldWriteBacks new JTextField jTextFieldWriteBacks setText 0 jTextFieldWriteBacks setEditable false jTextFieldWriteBacks setBackground Color WHITE return jTextFieldWriteBacks This method initializes jTextFieldWriteThroughs return javax swing JTextField EA private JTextField getJTextFieldWriteThroughs if jTextFieldWriteThroughs null jTextFieldWriteThroughs new JTextField jTextFieldWriteThroughs setText 0 jTextFieldWriteThroughs setEditable false jTextFieldWriteThroughs setBackground Color WHITE return jTextFieldWriteThroughs This method initializes jTextFieldNextLevel return javax swing JTextField x private JTextField getJTextFieldNextLevel if jTextFieldNextLevel null jTextFieldNextLevel new JTextField jTextFieldNextLevel setText 0 jTextFieldNextLevel setEditable false jTextFieldNextLevel setBackground Color WHITE return jTextFieldNextLevel This method initializes jTextFieldIAccess return javax swing JTextField private JTextField getJTextFieldIAccess if jTextFieldIAccess null jTextFieldIAccess new JTextField jTextFi
110. s setBackground c2 else this jTextFieldAcessos setBackground cl this jTextFieldAcessos setText tacessos numero de hits if Long parseLong this jTextFieldCacheHits getText hits this jTextFieldCacheHits setBackground c2 else this jTextFieldCacheHits setBackground cl this jTextFieldCacheHits setText hits numero de misses if Long parseLong this jTextFieldCacheMiss getText misses this jTextFieldCacheMiss setBackground c2 else this jTextFieldCacheMiss setBackground c1 this jTextFieldCacheMiss setText misses numero de write throughs if Long parseLong this jTextFieldWriteThroughs getText wr_throughs this jTextFieldWriteThroughs setBackground c2 else this jTextFieldWriteThroughs setBackground cl this jTextFieldWriteThroughs setText wr throughs numero de write backs if Long parseLong this jTextFieldWriteBacks getText wr backs this jTextFieldWriteBacks setBackground c2 else this jTextFieldWriteBacks setBackground cl this jTextFieldWriteBacks setText wr backs 61 116 Arquitectura Avan ada de Computadores Simulador de Cache numero de acessos ao proximo nivel long n next level Long parseLong jTextFieldNextLevel getText public public public public if n gt 2 this jTextFieldNextLevel setBackground c3 if n 1 this jTextFieldNextLevel setBackground c2 if n 0 this j
111. sses presentes neste ap ndice s o as seguintes o AboutDialog o Block o Cache o CacheSet o MainCanvas o MemAccess O MemAccessFile o MyPoint o NextLevelAccessDialog o RunProgram o SimParams o SimulationThread o SplitCache o SplitCacheDialog o UnifiedCache o UnifiedCacheDialog o WarningDialog 18 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 1 AboutDialog Esta classe serve unicamente para mostrar informa es sobre o trabalho realizado e sobre o autor A maior parte do c digo foi gerado automaticamente pelo ambiente de desenvolvimento package cacheSim import java awt BorderLayout import javax swing JFrame import javax swing JPanel import javax swing JDialog import javax swing JButton import javax swing JLabel import javax swing JTextArea import javax swing JScrollPane Dialogo sobre o autor do programa author Manuel zy public class AboutDialog extends JDialog public static final long serialVersionUID 0 private JPanel jContentPane null private JPanel jPanelCenter null private JButton jButtonOk null private JPanel jPanell null private JLabel jLabel null private JTextArea jTextArea null private JScrollPane jScrollPane null This is the default constructor xf public AboutDialog JFrame frame super frame Teste true initialize this setLocationRelativeTo null This method initializ
112. t java awt BorderLayout java awt Color java awt FlowLayout java awt Font java awt GridLayout javax swing BorderFactory javax swing ImageIcon javax swing JPanel javax swing JMenuItem javax swing JMenuBar javax swing JMenu javax swing JFrame javax swing JButton javax swing JLabel javax swing JTextField java awt ScrollPane javax swing JSlider Classe gr fica principal neste projecto a partir daqui pode se fazer tudo para saber como constituida simula o que se encarrega de actualizar esta interface public class RunProgram extends JFrame public static final long serialVersionUID 0 public static final int START SLEEP 1000 public static final int MIN SLEEP 1 public static final int MAX SLEEP 2000 private boolean nextLevelRegistry private NextLevelAccessDialog nextLevelDialog public MainCanvas myCanvas private SimulationThread animationThread private JPanel jContentPane null private JMenuBar jJMenuBar null private JMenu fileMenu null 58 116 Simulador de Cache Arquitectura Avan ada de Computadores Simulador de Cache private private private private private private private private private private private private private private private private private private private private private private private private private private private private private private private private p
113. tCache getDCache getNextLevelAccess if array null for int i 0 i array length i window addNextLevelAccess array i ERRADO Jelse if params isUnifiedCache window setNextDecodedAddress params getUnifiedCache getUCache getTag ma 78 116 Arquitectura Avan ada de Computadores Simulador de Cache params getUnifiedCache getUCache get Index ma params getUnifiedCache getUCache getOffset ma params getUnifiedCache getUCache getTagBits params getUnifiedCache getUCache getIndexBits params getUnifiedCache getUCache getOffsetBits params getUnifiedCache doMemAccess ma MemAccess array params getUnifiedCache getUCache getNextLevelAccess if array null for int i20 i array length i window addNextLevelAccess array i ERRADO showStatistcs catch Exception e System out println Access com o formato errado e getMessage WarningDialog dial new WarningDialog window Error Bad Access Format Ignoring access Mn te getMessage dial setVisible true jelse if pause this stepinto this stepinto false window myCanvas my x try if maf hasMore window resetStatistcsBackColor MemAccess ma maf getNext window setNextAccess ma RK K K k RIK RR RE RR EE RR Kk Ck Ck kk kk Ck ke kk ck k k ko ke ke RX ARX ke ke RX LE SPLIT CACHE Ri
114. tag this substituicao return acc Um acesso de escrita nunca provoca um hit Pode no m ximo proovar um write throug ou write back e deve ser assim que deve ser contabilizado para estatisticas Gparam ma acesso a mem ria do tipo write return private int doDataWriteAccess MemAccess ma long a ma getAddress a a gt gt this block size bits int set int a this sets this lastUsedSetIndex set FR X long tag ma getAddress gt gt this index size bits this block size bits int acc cache set doDataWriteAccess tag this substituicao this escrita return acc private int doInstructionAccess MemAccess ma 29 116 Arquitectura Avan ada de Computadores Simulador de Cache long a ma getAddress a a gt gt this block size bits calculo do conjunto int set int a 8 this sets this lastUsedSetIndex set calculo alternativo a ver se da os mesmos resultados long i a 32 bits al i i gt gt this index size bits i i lt lt this index size bits isa i int set int i resulta perfeitamente ambos as maneiras d o o mesmo resultado fim do calculo alternativo long tag ma getAddress gt gt this index size bits this block size bits int acc cache set doInstructionAccess tag this substituicao return acc this n_access this n instr access if acc 0 this n hitstt Jelsel this n misses
115. tatisticsin StatisticsWNn Cache cachel new Cache size block assoc sub true Cache cache2 new Cache size block assoc sub wr true SplitCache sCache new SplitCache cachel cache2 MemAccessFile maf new MemAccessFile args 5 int i for i 0 maf hasMore i try MemAccess ma maf getNext System out printin ma toString sCache doMemAccess ma catch Exception e System out println Bad Access Format maf close System out println Read tit instructions System out println nInstruction cachel printStatistcs SVS CCS UE PE CI Serres aterra seen sera nData Cache cache2 printStatistcs catch Exception e e printStackTrace 87 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 14 SplitCacheDialog Esta classe uma janela de di logo onde o utilizador altera as caracter sticas da cache e inicia simula o A maior parte do c digo gerada pela ferramenta de desenvolvimento package cacheSim import java awt BorderLayout import java awt Color import java awt Dimension import java awt FlowLayout import java awt GridLayout import javax swing BorderFactory import javax swing JFileChooser import javax swing JPanel import javax swing JDialog import javax swing JLabel import javax swing JTextField import javax swing JButton import javax swing JComboBox i
116. te long n dataread access private long n datawrite access private long n write backs private long n write throughs private long n access to next level false n o contabiliza as falhas compulsorias private int lastUsedSetIndex private MemAccess nextLevelAccessArray Construtor mais usado para criar uma cache param kb tamanho da cache em kilobytes Gparam block size tamanho de bloco da cache em bytes param substituicao politica de substitui o Gparam escrita politica de escrita throws CacheFormatException RX ox po Xx oOx private boolean falhas compulsorias true conta com as falhas compulsorias Gparam associatividade a associatividade da cache em multiplos de 2 ou 1 public Cache int kb int block size int associatividade final int substituicao final int escrita throws CacheFormatException this falhas_compulsorias true int size kb 1024 int blocks size block_size makeCache size blocks block_size associatividade escrita Pode contabilizar ou n o falhas compuls rias Gparam kb param block size Gparam associatividade param substituicao Gparam escrita throws CacheFormatException F F F F F X X substituicao Gparam falhas compulsorias true funciona como se n o tivesse argumento public Cache int kb int block size int associatividade final int substituicao final int escrita boolean falhas compulsorias
117. terface gr fica pode se concluir que os algoritmos de substitui o est o correctos 8 116 Arquitectura Avan ada de Computadores Simulador de Cache 2 5 3 Resultados do acesso Fizeram se testes unit rios para cada opera o de acesso e para cada estado poss vel do bloco escolhido a substituir os resultados apresentados a seguir mostram que todos os estados foram cobertos e que est de acordo com o funcionamento esperado de uma cache sendo assim f cil dizer com relativa confian a que os resultados obtidos ser o correctos tag igual tag diferente P dirty n o dirty dirty n o dirty 1 miss I Fs a hit 1 write back 1 miss next level dirty next level 2 next level miss DR rus SL 1 hit 1 write back Las 1 next level dirty 1 next level 2 next level 1 miss urs miss DW next level Lm ae IWON Backs 1 next level dirty dirty dirty 2 next level dirty dirty 9 116 Arquitectura Avan ada de Computadores Simulador de Cache 3 Conclus es Este trabalho apesar de inicialmente parecer simples revelou ser de alguma complexidade devido flexibilidade imposta na discrimina o da arquitectura da cache Fazer um simulador para um determinado tipo de cache por exemplo em que s variava o tamanho ou tamanho do bloco seria algo simples mas dar a hip tese ao utilizador de especificar pol ticas de substitui o pol ticas de escrita associa
118. tes replace policy LRU lt write policy write back write allocate M caracteristicas Instruction Cache da cache de I T i instru es ees kilobytes associativity 2 number of blocks per set blocksize 64 bytes replace policy v Next Level Access Log Cancel OK indica ser quer registo inicia a simula o dos acessos ao pr ximo n vel de mem ria 14 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 1 3 Correr a simula o Depois de escolher as caracter sticas da cache d se in cio simula o O utilizador tem tr s bot es de controlo play pause e next step O normal ser usar o next step para ver qual o acesso e qual o conjunto escolhido para esse acesso tamb m pode ver o endere o decomposto segundo as caracter sticas da cache tanto em bin rio como em decimal pr ximo passo da simula o amp my Cache Simulator EEES File Help on og acesso Address 001DFF58 Access Type R Access Size 8 00000000000111011111111 101 011000 Binary Address endere o gt decomposto SEK 5 za Decinal Address segundo as tag 23 bits index 3 bits offset 6 bits caracteristicas 3821 l Estatisticas da cache 2088950 2088944 Acessos 3461 2088944 Cache Hits 1001 3822 Cache Misses 2460 Write Throughs 0 Dea cache Writ h
119. throws CacheFormatException this falhas_compulsorias falhas_compulsorias int size kb 1024 int blocks size block_size makeCache size blocks block_size associatividade escrita substituicao Desaconselhado o uso deste construtor existe para alguma compatibilidade com vers es anteriores Gparam size tamanho da cache blocks block size param blocks numero de blocos param block size tamanho do bloco em n de bytes Gparam associatividade associatividade ou DIRECT MAPPING Gparam substituicao politica de substitui o WR param escrita politica de escrita em mem ria S throws CacheFormatException propriedades mal construidas 0X 0X F F F X 25 116 Arquitectura Avan ada de Computadores Simulador de Cache public Cache int size substituicao int escrita throvs CacheFormatException makeCache size FEZ private void makeCache int size int blocks associatividade int substituicao int escrita throws CacheFormatException int blocks int block_size blocks block_size size blocks blocks block_size block_size associatividade associatividade substituicao substituicao escrita escrita verifica es das propriedades da cache associatividade int block size int associatividade int substituicao escrita i int if size blocks block_size throw new Cache CacheFormatException Cache size different from block si
120. tisticas BorderLayout SOUTH return jPanelEstatisticas This method initializes jPanelEstatisticasControls return javax swing JPanel Fy private JPanel getJPanelEstatisticasControls if jPanelEstatisticasControls null jLabel10 new JLabel jLabel10 setText Next Level jLabe1l10 setHorizontalAlignment JLabel RIGHT jLabel9 new JLabel jLabel9 setText Write Throughs jLabel9 setHorizontalAlignment JLabel RIGHT 65 116 Arquitectura Avan ada de Computadores Simulador de Cache jLabel8 new JLabel jLabel8 setText Write backs jLabel8 setHorizontalAlignment JLabel RIGHT jLabel6 new JLabel jLabel6 setText Cache Misses jLabel6 setHorizontalAlignment JLabel RIGHT jLabel5 new JLabel jLabel5 setText Cache Hits jLabel5 setHorizontalAlignment JLabel RIGHT jLabel4 new JLabel jLabel4 setText jLabel3 new JLabel jLabel3 setText Estatisticas jLabel2 new JLabel jLabel2 setHorizontalAlignment JLabel RIGHT jLabel2 setText Acessos jPanelEstatisticasControls new JPanel jPanelEstatisticasControls setLayout new GridLayout 7 2 5 5 jPanelEstatisticasControls add jLabel4 jPanelEstatisticasControls add jLabel3 jPanelEstatisticasControls add jLabel2 jPanelEstatisticasControls add getJTextFieldAcessos jPanelEstatisticasControls add jLabel5 jPanelEstatist
121. tividade etc torna o problema em algo muito mais complexo sobretudo porque necess rio renderizar o esquema da cache Todos os requisitos impostos foram cumpridos e ainda foi implementada a pol tica de substitui o LRU A interface gr fica est bem desenhada sendo um programa de f cil utiliza o Pode se dizer que uma ferramenta interessante como complemento no ensino desta mat ria Em rela o ao desenvolvimento pode se dizer que o c digo est bastante modular e facilmente expans vel A linguagem escolhida para desenvolver este produto foi Java TM logo um software que pode correr em qualquer sistema operativo que possua uma Java Virtual Machine 10 116 Arquitectura Avan ada de Computadores Simulador de Cache 4 Melhoramentos Alguns melhoramentos que se podiam fazer em vers es futuras podiam ser a inclus o de um menu de configura o que desse hip tese ao utilizador de escolher v rios par metros da interface por exemplo se queria ver as tags em decimal hexadecimal ou bin rios etc Seriam funcionalidades secund rias que adicionariam algumas op es interessantes mas n o muito importantes Podia se incluir mais algumas estat sticas por exemplo falhas compuls rias e outras estat sticas que podessem ser interessantes para o programa Outro melhoramento a fazer talvez a inclus o de melhores anima es 11 116 Arquitectura Avan ada de Computadores Simulador de Cache 5 Refer nc
122. tle New Simulation this setSize 450 575 this setResizable false this setLocationRelativeTo null mainFrame frame This method initializes this Qreturn void a7 private void initialize this setPreferredSize new Dimension 400 400 this setContentPane getJContentPane This method initializes jContentPane Qreturn javax swing JPanel wre private JPanel getJContentPane if jContentPane null jContentPane new JPanel jContentPane setLayout new BorderLayout jContentPane add getJPanelCenter java awt BorderLayout CENTER jContentPane setBorder BorderFactory createEmptyBorder 10 10 10 10 return jContentPane This method initializes jPanelCenter return javax swing JPanel private JPanel getJPanelCenter if jPanelCenter null jPanelCenter new JPanel new BorderLayout jPanelCenter add getJPanel BorderLayout NORTH jPanelCenter add getJPanell13 java awt BorderLayout CENTER jPanelCenter add getJPanel12 java awt BorderLayout SOUTH return jPanelCenter This method initializes jPanel Qreturn javax swing JPanel XE private JPanel getJPanel if jPanel null jLabel new JLabel jLabel setText Trace File jPanel new JPanel new FlowLayout FlowLayout LEFT jPanel add jLabel null jPanel add getJTextFieldTraceFile null 90 116 Arquitectura Avan
123. tra para unified cache Na rea de desenho pode se ver o esquema da cache com os blocos representados por um rect ngulo e algumas informa es sobre qual a tag para cada bloco se o bloco est limpo se est dirty e informa o da cache Por ultimo o utilizador pode abrir uma janela de di logo em que pode ver os acessos ao n vel de mem ria superior e gravar para um ficheiro de texto 2 116 Arquitectura Avan ada de Computadores Simulador de Cache New Simulation X Trace File m kilobytes associativity number of blocks per set block size bytes replace policy write policy Instruction Cache size kilobytes associativity number of blocks per set block size 64 bytes replace policy write policy Cancel OK Figura 1 Cria o de uma nova simula o para split cache s my Cache Simulator File Help El e Lau Address 0703ff15 Access Type R Access Size 8 Estatisticas Split Cache i yale Se tan Acessos 99999 121590 Cache Hits 39999 clean 206 Cache Misses 99999 121590 121590 faltam estatisticas 97346 97346 121590 139 206 139 129823 Paused Figura 2 Interface principal 3 116 Arquitectura Avan ada de Computadores Simulador de Cache 2 2 Arquitectura A arquitectura deste programa bastante simples tem um objecto da classe RunProgram que representa a interfa
124. ut println ma toString uCache doMemAccess ma T maf close System out println Read tit instructions OVS CEI out POL ELS dE ere nUnified Cache Statistics em RE SE ERO EEES SES EE Wap cache printStatistcs catch Exception e e printStackTrace 102 116 Arquitectura Avan ada de Computadores Simulador de Cache 6 2 16 UnifiedCacheDialog Janela de dialogo onde o utilizador escolhe as caracteristicas da cache unificada e arranca a simula o package cacheSim import import import import import import import import import import import import import import java java java java java javax javax javax javax javax javax javax javax javax awt awt awt awt awt Swing B swing J swing J swing JDialog J J J swing swing swing swing JComboBox BorderLayout Color Dimension FlowLayout GridLayout orderFactory FileChooser Panel TextField Button swing JCheckBox Janela de dialogo com o utilizador para inserir os dados da cache unificada e o ficheiro de acessos author Manuel ay public class UnifiedCacheDialog extends JDialog private private private private private private private private private private private private private private private private private private private public static final
125. x if jTextFieldIndex null jTextFieldIndex new JTextField jTextFieldIndex setColumns 16 jTextFieldIndex setEditable false jTextFieldIndex setBackground Color WHITE jTextFieldIndex setFont new Font Courier Nem Font PLAIN return jTextFieldIndex This method initializes jTextFieldOffset return javax swing JTextField x private JTextField getJTextFieldOffset if jTextFieldOffset null jTextFieldOffset new JTextField jTextFieldOffset setColumns 16 jTextFieldOffset setEditable false jTextFieldOffset setBackground Color WHITE jTextFieldOffset return jTextFieldOffset This method initializes jPanelDecodedTop return javax swing JPanel xy private JPanel getJPanelDecodedTop if jPanelDecodedTop null jLabelBits new JLabel jLabelBits setText tag index offset jLabelBits setFont new Font Courier New Font PLAIN jPanelDecodedTop jPanelDecodedTop add jLabelBits null setFont new Font Courier New Font PLAIN 12 12 new JPanel new FlowLayout FlowLayout LEFT 73 116 Arquitectura Avan ada de Computadores Simulador de Cache return jPanelDecodedTop Qparam args XL public static void main String args TODO Auto generated method stub RunProgram application new RunProgram application setVisible true This is the default constructor
126. yItem write through write no allocate Cache WR THROUGH NO ALLOCATE return jComboBoxWritePolicy This method initializes jPanell2 return javax swing JPanel m f private JPanel getJPanell2 if jPanell2 null jPanell2 new JPanel new FlowLayout FlowLayout RIGHT jPanell2 add getJCheckBoxRegistry null jPanell2 add getJButtonCancel null jPanell2 add getJButtonOK null return jPanell2 This method initializes jButtonCancel return javax swing JButton private JButton getJButtonCancel if jButtonCancel null jButtonCancel new JButton jButtonCancel setText Cancel jButtonCancel jButtonCancel java awt event ActionListener public void actionPerformed java awt event ActionEvent e System out println simulationCancel Auto generated Event stub actionPerformed setPreferredSize labelDim addActionListener new TODO UnifiedCacheDialog this setVisible false return jButtonCancel 109 116 Arquitectura Avan ada de Computadores Simulador de Cache This method initializes jButtonOK return javax swing JButton A private JButton getJButtonOK if jButtonOK null jButtonOK new JButton jButtonOK setText OK jButtonOK setPreferredSize labelDim jButtonOK addActionListener new java awt event ActionListener public void actionPerformed java awt event Act
127. ze blocks if blocks associatividade 0 throw new Cache CacheFormatException Number of sets incompatible with number of blocks if block size 2 0 throw new Cache CacheFormatException Block size must be Dr 4 8 16 42 T 3 if associatividade this associatividade DIRECT MAPPING blocks if size 1 substituicao 0 JI blocks 1 escrita 0 block size 1 if substituicao 3 t if associatividade gt blocks HI escrita 3 impossivel this sets this cache int blocks associatividade new CacheSet this sets for i 0 i lt sets cache i i inicializando estatisticas this n hits 0 this n misses 0 this n access 0 this n dataread access this n datawrite access this n instr access 0 this n_access_to_next_level 0 0 0 calcular o numero de bits para o tamanho do block_size_bits 0 i block size while i 1 i i gt gt 1 block_size_bits calcula o numero de bits necess rios para o i sets index_size_bits 0 while i 1 i i gt gt 1 index_size_bits associatividade lt 0 throw new Cache CacheFormatException Wrong usage of arguments hrow new Cache CacheFormatException Wrong usage of arguments throw new Cache CacheFormatException Associatividade new CacheSet associatividade block size bloco index 26 116 Arquitectura Avan ada de Computado

Download Pdf Manuals

image

Related Search

Relat realtor relativity space relativity relationship related companies relativity login relationship synonym relationship goals movie relativism relative humidity relative frequency relational database related synonym related settings relative pronouns relatlimab relationship and pregnancy overhaul mod relatient login relative clauses related group relative permittivity relationship and pregnancy overhaul sims 4 relationship and pregnancy overhaul relativismo

Related Contents

ー 保管方法    Be inspired - Telekomunikacije  Spectacular image quality, outstanding brightness and  IMPORTANT SAFETY INSTRUCTIONS SAVE THESE  scd600-FR  USER MANUAL  the User Manual for this product  Synology RX415 disk array    

Copyright © All rights reserved.
Failed to retrieve file