Используя Node.js, у меня есть задача улучшить код, который я создал.Этот код выполняет 60 HTTP-запросов и использует для этого библиотеки.
Для выполнения всех HTTP-запросов и сохранения каждого в файл требуется 30 секунд!
Говорят, что эти запросы можно выполнить за 3 секунды с помощью:
1.Правильное управление асинхронными обещаниями
2.Немного умнее кеширование
3.Не используется кластер
4.Добавляйте накладные расходы только один раз
Я боюсь, что я не уверен, с чего начать, чтобы понять, что я могу сделать точно.
Так что ниже код получает массив из 60 элементов, где каждыйэто один HTTP-запрос:
const exchanges = ccxt.exchanges
Они входят в функцию: worker = async и в конце кода: await Promise.all (работники) ждут их завершения.
Я не уверен, с чего начать, чтобы на самом деле можно было опускаться до 3 секунд.Как можно улучшить скорость этого кода?
'use strict';
const ccxt = require ('ccxt')
, log = require ('ololog').noLocate // npm install ololog
, fs = require ('fs')
// the numWorkers constant defines the number of concurrent workers
// those aren't really threads in terms of the async environment
// set this to the number of cores in your CPU * 2
// or play with this number to find a setting that works best for you
, numWorkers = 8
;(async () => {
// make an array of all exchanges
const exchanges = ccxt.exchanges
.filter (id => ![ 'cap1', 'cap2' ].includes (id))
// instantiate each exchange and save it to the exchanges list
.map (id => new ccxt[id] ({
'enableRateLimit': true,
}))
// the worker function for each "async thread"
const worker = async function () {
// while the array of all exchanges is not empty
while (exchanges.length > 0) {
// pop one exchange from the array
const exchange = exchanges.pop()
// check if it has the necessary method implemented
if (exchange.has['fetchTickers']) {
// try to do "the work" and handle errors if any
try {
// fetch the response for all tickers from the exchange
const tickers = await exchange.fetchTickers()
// make a filename from exchange id
const filename = '/myproject/tickers/' + exchange.id + 'Tickers.json'
// save the response to a file
fs.writeFileSync(filename, JSON.stringify({ tickers }));
} catch (e) { } //Error
}
}
}
// create numWorkers "threads" (they aren't really threads)
const workers = [ ... Array (numWorkers) ].map (_ => worker ())
// wait for all of them to execute or fail
await Promise.all (workers)
}) ()