Performance, the fetch-execute cycle and interrupts · Desempenho, o ciclo fetch-execute e interrupções
| English | Português |
|---|---|
| interrupt/ˈɪntərʌpt/ | interrupção |
| clock speed/klɒk spiːd/ | velocidade do clock |
| fetch-execute cycle/fetʃ ˈeksɪkjuːt ˈsaɪkl/ | ciclo busca-execução |
| cores/kɔːz/ | núcleos |
| cache/kæʃ/ | cache |
| word size/wɜːd saɪz/ | tamanho da palavra |
| port/pɔːt/ | porta |
| peripheral/pəˈrɪfərəl/ | periférico |
| register transfer notation/ˈredʒɪstə ˈtrænsfɜː nəʊˈteɪʃn/ | notação de transferência de registrador |
| stack/stæk/ | pilha |
| interrupt service routine/ˈɪntərʌpt ˈsɜːvɪs ruːˈtiːn/ | rotina de serviço de interrupção |
| interrupt register/ˈɪntərʌpt ˈredʒɪstə/ | registrador de interrupção |
Why your laptop drops everything when you press a key
- A processor runs billions of cycles a second. If it had to stop and ask the keyboard "anything yet?" between instructions, it would waste most of them asking.
- Instead the keyboard sends an interrupt 中断. The processor finishes its current instruction, saves its place, deals with the key, and returns as if nothing had happened.
- That one mechanism is how a single processor appears to run your music, your browser and your typing at once.
- This lesson covers what makes a processor fast, how it connects to devices, exactly how it runs one instruction, and how an interrupt cuts in.
Por que seu laptop para tudo ao apertar uma tecla
- Um processador roda bilhões de ciclos por segundo. Se tivesse que parar e perguntar ao teclado "algo aí?" entre instruções, desperdiçaria a maioria delas fazendo perguntas.
- Em vez disso, o teclado envia uma interrupção 中断. O processador termina sua instrução atual, salva seu local, trata a tecla e retorna como se nada tivesse acontecido.
- Esse único mecanismo é como um único processador parece rodar música, navegador e digitação ao mesmo tempo.
- Esta lição cobre o que torna um processador rápido, como ele se conecta a dispositivos, exatamente como executa uma instrução e como uma interrupção entra em ação.
What affects performance
- Clock speed 时钟频率: more fetch-execute cycles a second, so more instructions a second, until heat sets the limit.
- Number of cores 核心: each core fetches and executes its own instruction at the same time, so several programs or threads run in parallel. A program must be written to use them, so doubling the cores does not double the speed.
- Bus width: a wider data bus moves more bits per transfer, so fewer transfers; a wider address bus reaches more memory.
- Cache 高速缓存: a small, fast memory next to the processor holding the instructions and data used most recently, so fewer slow trips to RAM. Word size 字长, the amount of RAM and the storage type help too.
O que afeta o desempenho
- Velocidade do clock 时钟频率: mais ciclos busca-executar por segundo, então mais instruções por segundo, até que o calor imponha limite.
- Número de núcleos 核心: cada núcleo busca e executa sua própria instrução ao mesmo tempo, permitindo que vários programas ou threads rodem em paralelo. Um programa deve ser escrito para usá-los, então dobrar os núcleos não dobra a velocidade.
- Largura do barramento: um barramento de dados mais largo move mais bits por transferência, reduzindo o número de transfers; um barramento de endereço mais largo alcança mais memória.
- Cache 高速缓存: uma pequena e rápida memória ao lado do processador guardando as instruções e dados usados mais recentemente, evitando viagens lentas à RAM. Tamanho de palavra 字长, quantidade de RAM e tipo de armazenamento também ajudam.
Select all · todos the factors that affect CPU performance. · Selecione todas os fatores que afetam o desempenho da CPU.
Clock speed, cores and cache (plus word size, RAM, storage and bus width) all affect performance. The case colour does not. · Velocidade do clock, núcleos e cache (mais largura de palavra, RAM, armazenamento e largura do barramento) afetam o desempenho. A cor da caixa não afeta.
A multi-core CPU is especially helpful for: · Uma CPU multi-núcleo é especialmente útil para:
Extra cores run tasks in parallel. A purely single-threaded job benefits more from higher per-core speed. · Núcleos extras executam tarefas em paralelo. Um trabalho puramente single-threaded se beneficia mais de velocidade por núcleo mais alta.
____ memory is a small, fast store next to the processor that holds recently used instructions and data, so fewer slow trips to RAM are needed. · ____ memory é um pequeno e rápido armazém ao lado do processador que segura instruções e dados usados recentemente, para fewer slow trips to RAM are needed.
More cache means more of the working set sits next to the processor, which is the reason it appears in every performance comparison. · Mais cache significa mais do conjunto de trabalho senta-se ao lado do processador, que é a razão pela qual aparece em todas as comparações de desempenho.
Worked example: "explain why the new computer is faster"
- Compare the two specifications line by line, each with its reason.
- 3.8 GHz against 2.4 GHz: more cycles a second, so more instructions executed a second.
- 8 cores against 4: twice as many instructions can be fetched and executed at the same time, for software that uses them.
- 16 MB of cache against 4 MB: more of the working set is held next to the processor, so fewer waits for RAM. Each line is two marks: the factor and its consequence.
Exemplo resolvido: "explique por que o novo computador é mais rápido"
- Compare as duas especificações linha por linha, cada uma com sua razão.
- 3.8 GHz contra 2.4 GHz: mais ciclos por segundo, portanto mais instruções executadas por segundo.
- 8 núcleos contra 4: duas vezes mais instruções podem ser buscadas e executadas simultaneamente, para software que os utilize.
- 16 MB de cache contra 4 MB: mais do conjunto ativo é mantido ao lado do processador, reduzindo esperas por RAM. Cada linha vale dois pontos: o fator e sua consequência.
Ports
- A port 端口 is a physical socket that connects a peripheral 外围设备.
- USB (Universal Serial Bus) is general-purpose: keyboards, drives, phones. It is plug-and-play: the computer detects the device, identifies it, loads its driver and can power it, with no restart.
- HDMI (High Definition Multimedia Interface) carries digital video and audio down one cable, so nothing is converted to analogue and the picture is not degraded. VGA (Video Graphics Array) is the older analogue video socket.
Portas
- Uma porta 端口 é um conector físico que liga um periférico 外围设备.
- USB (Universal Serial Bus) é multiuso: teclados, drives, telefones. É plug-and-play: o computador detecta o dispositivo, identifica-o, carrega seu driver e pode alimentá-lo, sem reinicialização.
- HDMI (High Definition Multimedia Interface) transmite vídeo digital e áudio por um único cabo, evitando conversão para analógico e degradação da imagem. VGA (Video Graphics Array) é a porta de vídeo analógica antiga.
Match each port to what it carries. · Combine cada porta ao que ela carrega.
Different signals, different sockets: an HDMI cable will not fit a USB port. · Sinais diferentes, soquetes diferentes: um cabo HDMI não entrará numa porta USB.
The fetch stage
- Once per instruction the processor runs the fetch-execute cycle 取指-执行周期. Fetch comes first, and the exam wants it in register transfer notation 寄存器传送记法.
- A read signal travels on the control bus, the address on the address bus, and the instruction comes back on the data bus. The PC is incremented straight after its address is copied, so that a jump executed later can still overwrite it.
PC → MAR → memory → MDR → CIR, with the PC incremented on the way
A etapa de busca
- Uma vez por instrução, o processador executa o ciclo busca-executar 取指-执行周期. A busca vem primeiro, e a prova exige que seja descrita em notação de transferência de registrador 寄存器传送记法.
MAR ← [PC] the address of the next instruction goes to the MAR
PC ← [PC] + 1 the PC now points to the following instruction
MDR ← [[MAR]] the instruction at that address is read into the MDR
CIR ← [MDR] the instruction is copied into the CIR for decoding
- Um sinal de leitura viaja pelo barramento de controle, o endereço pelo barramento de endereço, e a instrução retorna pelo barramento de dados. O PC é incrementado imediatamente após seu endereço ser copiado, para que um jump executado depois ainda possa sobrescrevê-lo.

PC → MAR → memória → MDR → CIR, com o PC incrementado no caminho
Put the fetch steps in the correct order. · Coloque os passos do fetch na ordem correta.
PC → MAR, increment PC, read signal, then the instruction travels MDR → CIR ready to decode. · PC → MAR, incrementa PC, sinal de leitura, então a instrução viaja MDR → CIR pronta para decodificar.
The PC is incremented during the fetch stage so the next cycle fetches the following instruction. · O PC é incrementado durante a etapa de busca para que o próximo ciclo busque a instrução seguinte.
Incrementing the PC early means it already points at the next instruction by the time this one executes (unless a jump changes it). · Incrementar o PC cedo significa que ele já aponta para a próxima instrução no momento em que esta é executada (a menos que um jump mude isso).
Decode, execute, repeat
- Decode: the control unit works out from the instruction in the CIR which operation it is and where its operands are.
- Execute: arithmetic and logic go to the ALU with the result in the ACC; a load or store moves data between memory and a register; a jump writes a new address into the PC.
- Then the cycle repeats from
MAR ← [PC]. At the end of every cycle the processor also checks whether an interrupt is waiting.
One LOAD and one ADD walk the registers: fetch, decode, execute, repeat
Decodificar, executar, repetir
- Decodificar: a unidade de controle determina, a partir da instrução no CIR, qual operação ela representa e onde estão seus operandos.
- Executar: aritmética e lógica vão para a ALU com o resultado no ACC; um load ou store move dados entre memória e registrador; um jump escreve um novo endereço no PC.
- Então o ciclo se repete a partir de
MAR ← [PC]. No final de cada ciclo, o processador também verifica se há uma interrupção pendente.
Um LOAD e um ADD percorrem os registradores: busca, decodificação, execução, repetição
The fetch-execute cycle · O ciclo fetch-execute
Tap round the loop the CPU repeats billions of times a second. Watch how fetch uses the PC/MAR/MDR/CIR registers, then decode and execute act on what was fetched. · Toque ao redor do loop que a CPU repete bilhões de vezes por segundo. Observe como o fetch usa os registradores PC/MAR/MDR/CIR, depois decode e execute agem sobre o que foi buscado.
Worked example: executing two instructions in notation
- Execute
LDD 200(load the contents of address 200 into the ACC):MAR ← 200, thenMDR ← [[MAR]], thenACC ← [MDR]. - Execute
ADD 201:MAR ← 201,MDR ← [[MAR]],ACC ← [ACC] + [MDR]. - Execute
STO 202:MAR ← 202,MDR ← [ACC],[[MAR]] ← [MDR]. - Every line moves one value between two places. The double brackets always mean "the memory location whose address is in the MAR".
Exemplo resolvido: executando duas instruções em notação
- Execute
LDD 200(carregue o conteúdo do endereço 200 no ACC):MAR ← 200, depoisMDR ← [[MAR]], depoisACC ← [MDR]. - Execute
ADD 201:MAR ← 201,MDR ← [[MAR]],ACC ← [ACC] + [MDR]. - Execute
STO 202:MAR ← 202,MDR ← [ACC],[[MAR]] ← [MDR]. - Cada linha move um valor entre dois locais. As colchetes duplos significam sempre "o local de memória cujo endereço está no MAR".
Put the register transfers that execute LDD 200 in order. · Coloque as transferências de registrador que executam LDD 200 em ordem.
Address to the MAR, contents of that address to the MDR, then into the accumulator. · Endereço para o MAR, conteúdo daquele endereço para o MDR, depois para o acumulador.
Interrupts
- An interrupt is a signal that pauses the normal cycle so the processor can deal with an urgent event.
- Causes: a hardware device (a key pressed, a printer buffer empty, a network packet arriving), a software fault (division by zero, an illegal instruction, arithmetic overflow), the operating system's timer marking the end of a time slice, a power-failure warning.
- Interrupts let the system respond promptly without the processor constantly checking devices, and they are how the operating system multitasks.
The cycle, with the interrupt check at the end of each pass
Interrupções
- Uma interrupção é um sinal que pausa o ciclo normal para que o processador possa lidar com um evento urgente.
- Causas: um dispositivo de hardware (uma tecla pressionada, um buffer de impressora vazio, um pacote de rede chegando), um erro de software (divisão por zero, uma instrução ilegal, overflow aritmético), o temporizador do sistema operacional marcando o fim de uma fatia de tempo, um aviso de falha de energia.
- As interrupções permitem que o sistema responda rapidamente sem que o processador verifique constantemente os dispositivos, e são como o sistema operacional faz multitarefa.

O ciclo, com a verificação de interrupção no final de cada passagem
An interrupt is: · Uma interrupção é:
An interrupt temporarily pauses the fetch-execute cycle so the CPU can service an urgent event, then resumes. · Uma interrupção pausa temporariamente o ciclo busca-execução para que a CPU possa atender a um evento urgente, e depois retoma.
Which of these can cause an interrupt? Select all · todos that apply. · Qual destes pode causar uma interrupção? Selecione todos os que se aplicam.
Hardware events, software faults and the OS timer all raise interrupts. A loop ending is ordinary program flow handled by a jump, not an interrupt. · Eventos de hardware, falhas de software e o temporizador do SO geram interrupções. O fim de um loop é fluxo de programa ordinário manipulado por um jump, não uma interrupção.
Handling an interrupt
- Finish the current instruction. Save the state: the contents of the PC and the other registers go onto the stack 栈.
- Load the address of the interrupt service routine 中断服务程序 (ISR) into the PC and run it. The ISR handles the event.
- Restore the saved state from the stack and carry on with the interrupted program exactly where it left off.
Save, service, restore, resume
Lidando com uma interrupção
- Termine a instrução atual. Salve o estado: o conteúdo do PC e dos outros registradores vai para a pilha 栈.
- Carregue o endereço da rotina de serviço de interrupção 中断服务程序 (ISR) no PC e execute-a. A ISR trata o evento.
- Restaurar o estado salvo da pilha e continuar com o programa interrompido exatamente onde parou.

Salvar, servir, restaurar, retomar
When an interrupt occurs, the CPU first finishes the current instruction, then: · Quando uma interrupção ocorre, a CPU primeiro termina a instrução atual, e depois:
It saves the PC and registers, runs the interrupt service routine, then restores the state and continues where it left off. · Ela salva o PC e os registradores, executa a rotina de serviço de interrupção, e depois restaura o estado e continua de onde parou.
Worked example: the four-mark interrupt answer
- Explain how an interrupt from an input device is detected and handled in the fetch-execute cycle.
- The device sends an interrupt signal that sets a flag in the interrupt register 中断寄存器. The processor checks that register at the end of every cycle, after the current instruction has finished executing.
- If a flag is set and the interrupt has a higher priority than the current task, the PC and the other registers are saved on the stack. The address of the ISR is loaded into the PC and the routine runs.
- When it finishes, the registers are restored from the stack and the interrupted program resumes. Four points, in that order.
Exemplo resolvido: a resposta de interrupção de quatro pontos
- Explique como uma interrupção de um dispositivo de entrada é detectada e manipulada no ciclo busca-execução.
- O dispositivo envia um sinal de interrupção que define uma flag no registrador de interrupção 中断寄存器. O processador verifica esse registrador no final de cada ciclo, após a instrução atual ter sido executada.
- Se uma flag estiver definida e a interrupção tiver prioridade maior que a tarefa atual, o PC e os outros registradores são salvos na pilha. O endereço da ISR é carregado no PC e a rotina é executada.
- Quando termina, os registradores são restaurados da pilha e o programa interrompido retoma. Quatro pontos, nessa ordem.
The processor checks for interrupts at the end of every fetch-execute cycle, after the current instruction has finished. · O processador verifica interrupções no final de cada ciclo busca-execução, após a instrução atual ter terminado.
That timing is what lets the state be saved cleanly: no instruction is ever left half done. · Esse timing é o que permite salvar o estado limamente: nenhuma instrução fica metade executada.
Marks that slip away
- The PC is incremented during the fetch, not after the execute. Put
PC ← [PC] + 1second, straight afterMAR ← [PC]. - Interrupts are checked at the end of a cycle, never in the middle of an instruction.
- The state goes onto the stack and comes back from it. "The CPU stops" or "the program is lost" is wrong: it resumes exactly where it was.
- More cores do not double the speed; the software has to use them. Say so when comparing specifications.
Marcas que escapam
- O PC é incrementado durante a busca, não após a execução. Coloque
PC ← [PC] + 1em segundo lugar, logo apósMAR ← [PC]. - As interrupções são verificadas no final de um ciclo, nunca no meio de uma instrução.
- O estado vai para a pilha e volta dela. "A CPU para" ou "o programa é perdido" está errado: ele retoma exatamente onde estava.
- Mais núcleos não dobram a velocidade; o software precisa usá-los. Diga isso ao comparar especificações.
You've got it
- performance: clock speed, cores, bus width, cache (plus word size, RAM, storage), each with its consequence
- ports: USB general-purpose and plug-and-play, HDMI digital video and audio, VGA analogue video
- fetch:
MAR ← [PC],PC ← [PC] + 1,MDR ← [[MAR]],CIR ← [MDR]; then decode, execute, repeat - an interrupt is checked at the end of each cycle: save state on the stack, run the ISR, restore, resume
Entendeu?
- desempenho: velocidade do clock, núcleos, largura do barramento, cache (mais tamanho de palavra, RAM, armazenamento), cada um com sua consequência
- portas: USB de uso geral e plug-and-play, HDMI de vídeo e áudio digitais, VGA analógica
- busca:
MAR ← [PC],PC ← [PC] + 1,MDR ← [[MAR]],CIR ← [MDR]; depois decodificar, executar, repetir - uma interrupção é verificada no final de cada ciclo: salvar estado na pilha, executar a ISR, restaurar, retomar