-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirst.rb
184 lines (137 loc) · 5.79 KB
/
first.rb
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# frozen_string_literal: true
require "time"
=begin
Реализовал quicksort. Сказать что хорошо получилось не могу. Очень много работы с файлами.
________________________________________________________
Executed in 25.67 secs fish external
usr time 3.89 secs 1.03 millis 3.89 secs
sys time 13.50 secs 0.00 millis 13.50 secs
Вот это говорит о том, что 80% времени процессор тратит на работу с файлами. Системные вызовы.
И это на 15к записей, это очень долго. Если загрузить в оперативку и отсортировать рубишным sort то будет пара секунд,
а для баз данных это вообще смешные объёмы.
Возможно сортировка пузырьком была бы быстрее, там просто 2 соседние строки меняются местами, можно вообще сортировать
без дополнительных файлов.
Можно саму работу с файлами попробовать оптимизировать, не открывать новые файлы, а использовать один файл как кучу.
Можно попробовать использовать доступную оперативку и часть шагов делать в ней, если влезают.
После оптимизации системных вызовов, если время всё ещё не устраивает, можно попробовавть предварительно обработать
файл, что бы с ним было удобнее работать.
Например если выравнить записи о транзакциях по занимаемому месту можно будет ссылаться сразу на нужную строку.
Можно будет менять произвольные строки местами.
Ещё можно попробовать вместо постоянного парсинга сразу преобразовать все строки в Marshal.dump
и читать их через Marshal.load
Заниматься всем этим бесплатно я не хочу, по этому оставлю как получилось.
=end
module First
COPY_BUFFER_SIZE = 1024 * 1024
class Transaction
attr_reader :transaction_id, :user_id
def initialize(time:, transaction_id:, user_id:, amount:)
@_time = time
@_amount = amount
@transaction_id = transaction_id
@user_id = user_id
end
def time
@time ||= Time.parse(@_time)
end
def amount
@amount ||= BigDecimal(@_amount)
end
end
def self.generate(number, &block)
number.to_i.times do
time = Time.at(rand(10_000_000_000))
transaction_id = "txn#{rand(10_000_000_000_000)}"
user_id = "user#{rand(1_000_000)}"
amount = rand(1_000_000_000) / 1000.0
block.call("#{time}, #{transaction_id}, #{user_id}, #{amount}")
end
end
def self.copy(input, output, first_byte, last_byte)
input.seek(first_byte)
loop do
size = last_byte - input.tell
size = COPY_BUFFER_SIZE if size > COPY_BUFFER_SIZE
data = input.read(size)
break if data.nil?
break if data.empty?
output.write(data)
end
end
def self.parse(data)
time, transaction_id, user_id, amount = data.chomp.split(/, */)
Transaction.new(time:, transaction_id:, user_id:, amount:)
end
def self.sort_step(input, output, borders)
puts "step: #{input.inspect} -> #{output.inspect}; borders: #{borders}"
more = File.open("tmp/more.log", "w+")
less = File.open("tmp/less.log", "w+")
new_steps = []
base_line = nil
base_transaction = nil
copy(input, output, 0, borders.first)
input.each_line do |line|
if base_line.nil?
base_line = line
base_transaction = parse(base_line)
else
transaction = parse(line)
if transaction.amount < base_transaction.amount
more.write(line)
else
less.write(line)
end
end
break unless borders.include?(input.tell)
end
if less.size.positive?
from_byte = output.tell
copy(less, output, 0, less.size)
to_byte = output.tell
new_steps.push(from_byte...to_byte)
end
unless base_line.nil?
output.write(base_line)
end
if more.size.positive?
from_byte = output.tell
copy(more, output, 0, more.size)
to_byte = output.tell
new_steps.push(from_byte...to_byte)
end
copy(input, output, borders.last, input.size)
new_steps
end
def self.sort(file_name)
original = File.open(file_name, "r")
input = File.open("tmp/input.log", "w")
original.each_line do |line|
input.write(line)
end
size = input.size
input.close
steps = []
steps.push(0...size)
while (borders = steps.shift)
puts "steps in queue: #{steps.size}"
input = File.open("tmp/input.log", "r")
output = File.open("tmp/step.log", "w")
new_steps = sort_step(input, output, borders)
steps.concat(new_steps)
File.rename(output, "tmp/input.log")
input.close
output.close
end
File.rename(input, "result.log")
input.close
end
def self.check_sort(file_name)
input = File.open(file_name, "r")
current_transaction = parse(input.readline)
input.each_line do |next_line|
next_transaction = parse(next_line)
raise "so bad" unless current_transaction.amount >= next_transaction.amount
current_transaction = next_transaction
end
end
end