-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBelady.go
More file actions
121 lines (101 loc) · 2.35 KB
/
Copy pathBelady.go
File metadata and controls
121 lines (101 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package main
import (
"bufio"
"flag"
"fmt"
"os"
"strconv"
"strings"
)
type Access struct {
Timestamp int
PageID int
}
type BeladyMemory struct {
capacity int
trace []Access
memory map[int]bool
}
func NewBeladyMemory(capacity int, trace []Access) BeladyMemory {
return BeladyMemory{
capacity: capacity,
trace: trace,
memory: make(map[int]bool),
}
}
func findNextUse(trace []Access, currentIndex int, pageID int) int {
for i := currentIndex + 1; i < len(trace); i++ {
if trace[i].PageID == pageID {
return i
}
}
return -1
}
func (bc BeladyMemory) findPageToEvict(currentIndex int) int {
farthestIndex := -1
pageToEvict := -1
for page := range bc.memory {
nextUse := findNextUse(bc.trace, currentIndex, page)
if nextUse == -1 {
return page
}
if nextUse > farthestIndex {
farthestIndex = nextUse
pageToEvict = page
}
}
return pageToEvict
}
func (bc BeladyMemory) Simulate() {
hits, misses := 0, 0
fmt.Printf("timestamp,pageID,status\n")
for i, access := range bc.trace {
pageID := access.PageID
if _, found := bc.memory[pageID]; found {
fmt.Printf("%d,%d,HIT\n", access.Timestamp, pageID)
hits++
} else {
fmt.Printf("%d,%d,MISS\n", access.Timestamp, pageID)
misses++
if len(bc.memory) >= bc.capacity {
pageToEvict := bc.findPageToEvict(i)
delete(bc.memory, pageToEvict)
}
bc.memory[pageID] = true
}
}
fmt.Printf("Total Hits: %d, Total Misses: %d\n", hits, misses)
}
func readTraceBelady(filename string) ([]Access, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
var trace []Access
scanner := bufio.NewScanner(file)
scanner.Scan()
for scanner.Scan() {
line := scanner.Text()
fields := strings.Split(line, ",")
timestamp, _ := strconv.Atoi(fields[0])
pageID, _ := strconv.Atoi(fields[1])
trace = append(trace, Access{Timestamp: timestamp, PageID: pageID})
}
if err := scanner.Err(); err != nil {
return nil, err
}
return trace, nil
}
func main() {
capacity := flag.Int("capacity", 4, "Capacidade do memory de Belady")
inputFile := flag.String("input", "trace.csv", "Arquivo CSV contendo o trace de acessos")
flag.Parse()
trace, err := readTraceBelady(*inputFile)
if err != nil {
fmt.Println("Erro ao ler o trace:", err)
return
}
BeladyMemory := NewBeladyMemory(*capacity, trace)
BeladyMemory.Simulate()
}