-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparalelismo.ts
43 lines (37 loc) · 1.65 KB
/
paralelismo.ts
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
class ParallelProcessor {
async simulateAsyncTask(message: string, delay: number) {
console.log(`Iniciando processamento: ${message}`);
await new Promise((resolve) => setTimeout(resolve, delay)); // Simula uma tarefa assíncrona
console.log(`Finalizando processamento: ${message}`);
}
async processMessagesInParallel(messages: Array<string>) {
const MAX_CONCURRENT_TASKS = 32; // Quantidade máxima de tarefas simultâneas
// Divide as mensagens em chunks para respeitar o limite de paralelismo
const chunks = this.chunkArray(messages, MAX_CONCURRENT_TASKS);
for (const chunk of chunks) {
// Processa as mensagens no chunk em paralelo
await Promise.all(
chunk.map((message) => this.simulateAsyncTask(message, 2000)) // Simula 2 segundos de atraso por mensagem
);
}
}
chunkArray(array: Array<any>, size: number): Array<Array<any>> {
const result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
async testParallelProcessing() {
const testMessages = Array.from({ length: 50 }, (_, i) => `Mensagem ${i + 1}`); // 50 mensagens fictícias
console.time('Total Processing Time'); // Inicia o timer para medir o tempo total
await this.processMessagesInParallel(testMessages);
console.timeEnd('Total Processing Time'); // Finaliza o timer e imprime o tempo total
console.log('Processamento completo!');
}
}
// Executa o teste
(async () => {
const processor = new ParallelProcessor();
await processor.testParallelProcessing();
})();