Skip to content

Instantly share code, notes, and snippets.

@b1naryth1ef
Created May 7, 2018 16:53
Show Gist options
  • Save b1naryth1ef/4da274b2f10a69bb747a2b8cddbf8120 to your computer and use it in GitHub Desktop.
Save b1naryth1ef/4da274b2f10a69bb747a2b8cddbf8120 to your computer and use it in GitHub Desktop.
import gc
import sys
from datetime import datetime
from collections import Counter
from disco.bot import Plugin, CommandLevels
class MemoryDebugPlugin(Plugin):
@staticmethod
def _get_memory_counters():
by_count = Counter()
by_size = Counter()
for obj in gc.get_objects():
by_count[type(obj).__name__] += 1
by_size[type(obj).__name__] = sys.getsizeof(obj)
return by_count, by_size
@Plugin.command('top', group='memory', level=CommandLevels.TRUSTED)
def memory_top(self, event):
by_count, by_size = self._get_memory_counters()
codeblock = '```python\n{}\n```'
event.msg.reply('\nBy Count: {}\n By Size: {}\n'.format(
codeblock.format('\n'.join('{}: {}'.format(k, v) for k, v in by_count.most_common(15))),
codeblock.format('\n'.join('{}: {}'.format(k, v) for k, v in by_size.most_common(15))),
))
@Plugin.command('debug', group='memory', level=CommandLevels.TRUSTED)
def memory_debug(self, event):
data = 'Disco Memory Debug ({})\n'.format(datetime.utcnow().isoformat())
by_count, by_size = self._get_memory_counters()
data += '\nObjects By Count: \n\n'
data += '\n'.join('{}: {}'.format(k, v) for k, v in by_count.most_common(250))
data += '\nObjects By Size: \n\n'
data += '\n'.join('{}: {}'.format(k, v) for k, v in by_size.most_common(250))
data += '\nStore Stats: \n'
data += 'Guilds: {}\n'.format(len(self.state.guilds))
data += 'DMs: {}\n'.format(len(self.state.dms))
data += 'Channels: {}\n'.format(len(self.state.channels))
data += 'Users: {}\n'.format(len(self.state.users))
data += 'Voice States: {}\n'.format(len(self.state.voice_states))
event.msg.reply(attachments=[('memory_debug.txt', data)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment