简体   繁体   English

命令需要很长时间才能完成

[英]Command takes too long to complete

My code for this, I admit is not great however I have been testing for a couple of days now and I cannot seem to improve it.我的代码,我承认不是很好,但是我已经测试了几天,我似乎无法改进它。

Basically I am using the module systeminformation : Docs基本上我正在使用模块systeminformation : Docs

My issue currently is that when running my command, it takes on average 7 seconds to complete and send the embed, I am sending the complete code in the hopes of the reader having a better understanding of what is happening.我目前的问题是,在运行我的命令时,完成和发送嵌入平均需要 7 秒,我正在发送完整的代码,希望读者能够更好地了解正在发生的事情。 When I first wrote the code, none of the data from systeminformation was under await, this caused the bot to crash due to it trying to send the embed before it gets the information.当我第一次写的代码,没有从数据的systeminformation是下的await,这引起了机器人崩溃,由于它试图发送嵌入它得到的信息之前。

const { MessageEmbed } = require('discord.js');
const si = require('systeminformation');

module.exports = {
    config: {
        name: 'stats',
        usage: '${prefix}stats',
        category: 'informative',
        description: 'Displays stats about the bot',
        accessableby: 'Everyone',
    },
    run: async (bot, message) => {

        console.time() // Just a way for me to check how long it takes to complete
        function convertMS(ms) {
            let d, h, m, s;
            s = Math.floor(ms / 1000);
            m = Math.floor(s / 60);
            s = s % 60;
            h = Math.floor(m / 60);
            m = m % 60;
            d = Math.floor(h / 24);
            h = h % 24;
            return {
                d: d,
                h: h,
                m: m,
                s: s,
            };
        }

        const u = convertMS(bot.uptime);
        const uptime =
            u.d +
            ' days, ' +
            u.h +
            ' hours, ' +
            u.m +
            ' minutes, ' +
            u.s +
            ' seconds';

        const msg = await message.channel.send('Generating...');
        message.channel.startTyping();
        let ping = Math.round(bot.ws.ping);
        await si.mem().then(data => totalMemory = Math.floor(data.total / 1024 / 1024));
        await si.mem().then(data => swapMem = Math.floor(data.swapused / 1024 / 1024));
        await si.mem().then(data => cachedMem = Math.floor(data.cached / 1024 / 1024));
        await si.mem().then(data => memoryUsed = Math.floor(data.used / 1024 / 1024));
        let realMemUsed = Math.floor(cachedMem - swapMem + memoryUsed);
        let memPercent = Math.floor(realMemUsed / totalMemory * 100);
        await si.currentLoad().then(data => cpuUsage = Math.floor(data.currentload_user));
        await si.osInfo().then(data => osVersion = data.distro);
        await si.versions().then(data => nodeVersion = data.node);

        msg.delete();
        const serverembed = new MessageEmbed()
            .setAuthor('Ragnarok Info', bot.user.avatarURL())
            .setFooter(`Bot Created • November 4, 2018`)
            .setColor('#7289DA')
            .setThumbnail(bot.user.avatarURL())
            .addFields({
                name: 'Owner',
                value: 'Ragnar Lothbrok#1948',
                inline: true
            }, {
                name: 'Uptime',
                value: uptime
            }, {
                name: 'Memory Usage',
                value: `${realMemUsed} / ${totalMemory} - ${memPercent}%`,
                inline: true
            }, {
                name: 'CPU Usage',
                value: `${cpuUsage}%`,
                inline: true
            }, {
                name: 'Ping',
                value: `${ping}ms`,
                inline: true
            }, {
                name: 'Users',
                value: bot.users.cache.size,
                inline: true
            }, {
                name: 'Versions',
                value: `OS: ${osVersion}\nNode.js: ${nodeVersion}\nDiscord.js: v12`,
                inline: true
            }, {
                name: 'Guilds',
                value: bot.guilds.cache.size,
                inline: true
            }, {
                name: 'Announcements',
                value: '```N/A```',
            });
        message.channel.send(serverembed);
        message.channel.stopTyping();

        console.timeEnd() // Just a way for me to check how long it takes to complete

    },
};

The reason why it's taking so much time to complete is because you are waiting for each of the promises to resolve before continuing.之所以要花费如此多的时间来完成,是因为在继续之前,您正在等待每个承诺都得到解决。 It would be worth storing the result of si.mem() and then taking the values from there.值得存储si.mem()的结果,然后从那里获取值。

const memory = await si.mem();
const totalMemory = Math.floor(memory.total / 1024 / 1024);
const swapMem = Math.floor(memory.swapused / 1024 / 1024);
const cachedMem = Math.floor(memory.cached / 1024 / 1024);
const memoryUsed = Math.floor(memory.used / 1024 / 1024);

Another improvement would be to cache the results of si.osInfo() and si.versions() .另一个改进是缓存si.osInfo()si.versions() Because these will not change during the runtime of your progam.因为这些在您的程序运行期间不会改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM