本文整理汇总了Python中humanfriendly.format_size方法的典型用法代码示例。如果您正苦于以下问题:Python humanfriendly.format_size方法的具体用法?Python humanfriendly.format_size怎么用?Python humanfriendly.format_size使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类humanfriendly
的用法示例。
在下文中一共展示了humanfriendly.format_size方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: initializeTorrent
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def initializeTorrent(self):
self.torrent = dottorrent.Torrent(self.inputEdit.text())
try:
t_info = self.torrent.get_info()
except Exception as e:
self.torrent = None
self._showError(str(e))
return
ptail = os.path.split(self.torrent.path)[1]
if self.inputMode == 'file':
self._statusBarMsg(
"{}: {}".format(ptail, humanfriendly.format_size(
t_info[0], binary=True)))
else:
self._statusBarMsg(
"{}: {} files, {}".format(
ptail, t_info[1], humanfriendly.format_size(
t_info[0], binary=True)))
self.pieceSizeComboBox.setCurrentIndex(0)
self.updatePieceCountLabel(t_info[2], t_info[3])
self.pieceCountLabel.show()
self.createButton.setEnabled(True)
示例2: model_summary
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def model_summary(model: torch.nn.Module) -> str:
message = "Model structure:\n"
message += str(model)
num_params = get_human_readable_count(
sum(p.numel() for p in model.parameters() if p.requires_grad)
)
message += "\n\nModel summary:\n"
message += f" Class Name: {model.__class__.__name__}\n"
message += f" Number of parameters: {num_params}\n"
num_bytes = humanfriendly.format_size(
sum(
p.numel() * to_bytes(p.dtype) for p in model.parameters() if p.requires_grad
)
)
message += f" Size: {num_bytes}\n"
dtype = next(iter(model.parameters())).dtype
message += f" Type: {dtype}"
return message
示例3: format_stats
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def format_stats(stats):
result = " \n"
result += "File types | Count | Total Size\n"
result += ":-- | :-- | :-- \n"
counter = 0
for mime in stats["ext_stats"]:
result += mime[2]
result += " | " + str(mime[1])
result += " | " + humanfriendly.format_size(mime[0]) + " \n"
counter += 1
if counter >= 3:
break
result += "**Total** | **" + str(stats["total_count"]) + "** | **"
result += humanfriendly.format_size(stats["total_size"]) + "** \n\n"
return result
示例4: updatePieceCountLabel
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def updatePieceCountLabel(self, ps, pc):
ps = humanfriendly.format_size(ps, binary=True)
self.pieceCountLabel.setText("{} pieces @ {} each".format(pc, ps))
示例5: _get_column_sizes_human_readable
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def _get_column_sizes_human_readable(self):
column_count = self._get_columns_len()
page_size = self._getpagesize()
column_sizes = []
for c in range(0, column_count):
size = humanfriendly.format_size((2**c) * page_size, binary=True)
column_sizes.append(size)
return ' '.join(column_sizes)
示例6: status
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def status(cmd, pld):
"""
:param cmd: The command object referenced in the command.
:type cmd: sigma.core.mechanics.command.SigmaCommand
:param pld: The payload with execution data and details.
:type pld: sigma.core.mechanics.payload.CommandPayload
"""
uptime_set = arrow.utcnow().float_timestamp - cmd.bot.start_time.float_timestamp
processed = round(cmd.bot.queue.processed / uptime_set, 3)
os_icon, os_color = get_os_icon()
general_text = f'Latency: **{int(cmd.bot.latency * 1000)}ms**'
general_text += f'\nPlatform: **{sys.platform.upper()}**'
general_text += f'\nStarted: **{arrow.get(psutil.boot_time()).humanize()}**'
cpu_clock = psutil.cpu_freq()
cpu_clock = round(cpu_clock.current, 2) if cpu_clock else '???'
cpu_text = f'Count: **{psutil.cpu_count()} ({psutil.cpu_count(logical=False)})**'
cpu_text += f'\nUsage: **{psutil.cpu_percent()}%**'
cpu_text += f'\nClock: **{cpu_clock} MHz**'
avail_mem = psutil.virtual_memory().available
total_mem = psutil.virtual_memory().total
used_mem = humanfriendly.format_size(total_mem - avail_mem, binary=True)
total_mem = humanfriendly.format_size(total_mem, binary=True)
sigma_mem = humanfriendly.format_size(psutil.Process(os.getpid()).memory_info().rss, binary=True)
mem_text = f'Me: **{sigma_mem}**'
mem_text += f'\nUsed: **{used_mem}**'
mem_text += f'\nTotal: **{total_mem}**'
response = discord.Embed(color=os_color)
response.set_author(name=socket.gethostname(), icon_url=os_icon)
response.add_field(name='General', value=general_text)
response.add_field(name='CPU', value=cpu_text)
response.add_field(name='Memory', value=mem_text)
if cmd.bot.cfg.dsc.bot:
shard_latency = get_shard_latency(cmd.bot.latencies, pld.msg.guild.shard_id)
verbose_description = f'Shard: #{pld.msg.guild.shard_id} | '
verbose_description += f'Latency: {shard_latency}ms | '
verbose_description += f'Activity: {processed} ev/s'
response.description = verbose_description
await pld.msg.channel.send(embed=response)
示例7: log_step_message
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def log_step_message(self, header, losses, speeds, comparative_loss, batch_size, is_training, tag=""):
def get_loss_color(old_loss: float, new_loss: float):
if old_loss < new_loss:
return "red"
else:
return "green"
def get_log_color(is_training: bool):
if is_training:
return {"color": "blue",
"attrs": ["bold"]}
else:
return {"color": "yellow",
"attrs": ["underline"]}
self.last_loss.setdefault(tag, comparative_loss)
loss_color = get_loss_color(self.last_loss.get(tag, 0), comparative_loss)
self.last_loss[tag] = comparative_loss
model_size = hf.format_size(self.model.total_params*4)
total_params = hf.format_number(self.model.total_params)
loss_desc, loss_val = self.build_info_step_message(losses, "{:7.4f}")
header_desc, header_val = self.build_duration_step_message(header)
speed_desc, speed_val = self.build_info_step_message(speeds, "{:4.0f}")
with utils.format_text(loss_color) as fmt:
loss_val_colored = fmt(loss_val)
msg = (
f"[{tag}] {header_desc}: {header_val}\t"
f"{speed_desc}: {speed_val} ({self.args.width},{self.args.height};{batch_size})\t"
f"{loss_desc}: {loss_val_colored} "
f"| {model_size} {total_params}")
with utils.format_text(**get_log_color(is_training)) as fmt:
self.log.info(fmt(msg))
示例8: human_throttle
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def human_throttle(throttle):
if throttle is None:
return "N/A"
return humanfriendly.format_size(int(throttle), binary=True)
示例9: fetch_worker
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def fetch_worker(url):
"""
Fetch the given URL for :func:`fetch_concurrent()`.
:param url: The URL to fetch (a string).
:returns: A tuple of three values:
1. The URL that was fetched (a string).
2. The data that was fetched (a string or :data:`None`).
3. The number of seconds it took to fetch the URL (a number).
"""
# Ignore Control-C instead of raising KeyboardInterrupt because (due to a
# quirk in multiprocessing) this can cause the parent and child processes
# to get into a deadlock kind of state where only Control-Z will get you
# your precious terminal back; super annoying IMHO.
signal.signal(signal.SIGINT, signal.SIG_IGN)
timer = Timer()
try:
data = fetch_url(url, retry=False)
except Exception as e:
logger.debug("Failed to fetch %s! (%s)", url, e)
data = None
else:
kbps = format_size(round(len(data) / timer.elapsed_time, 2))
logger.debug("Downloaded %s at %s per second.", url, kbps)
return url, data, timer.elapsed_time
示例10: _formatSize
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def _formatSize(size):
return humanfriendly.format_size(size, binary=True)
示例11: log_step_message
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def log_step_message(self, header, losses, speeds, comparative_loss, batch_size, is_training, tag=""):
def get_loss_color(old_loss: float, new_loss: float):
if old_loss < new_loss:
return "red"
else:
return "green"
def get_log_color(is_training: bool):
if is_training:
return {"color": "blue",
"attrs": ["bold"]}
else:
return {"color": "yellow",
"attrs": ["underline"]}
self.last_loss.setdefault(tag, comparative_loss)
loss_color = get_loss_color(self.last_loss.get(tag, 0), comparative_loss)
self.last_loss[tag] = comparative_loss
model_size = hf.format_size(self.model.total_params*4)
total_params = hf.format_number(self.model.total_params)
loss_desc, loss_val = self.build_info_step_message(losses, "{:7.4f}")
header_desc, header_val = self.build_duration_step_message(header)
speed_desc, speed_val = self.build_info_step_message(speeds, "{:4.0f}")
with utils.format_text(loss_color) as fmt:
loss_val_colored = fmt(loss_val)
msg = (
f"[{tag}] {header_desc}: {header_val}\t"
f"{speed_desc}: {speed_val} ({self.input_shape};{batch_size})\t"
f"{loss_desc}: {loss_val_colored} "
f"| {model_size} {total_params}")
with utils.format_text(**get_log_color(is_training)) as fmt:
self.log.info(fmt(msg))
示例12: _write_summary
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def _write_summary(manager: PoolManager) -> None:
print('Cluster statistics:')
total_cpus = manager.cluster_connector.get_resource_total('cpus')
total_mem = format_size(manager.cluster_connector.get_resource_total('mem') * 1000000)
total_disk = format_size(manager.cluster_connector.get_resource_total('disk') * 1000000)
total_gpus = manager.cluster_connector.get_resource_total('gpus')
allocated_cpus = manager.cluster_connector.get_resource_allocation('cpus')
allocated_mem = format_size(manager.cluster_connector.get_resource_allocation('mem') * 1000000)
allocated_disk = format_size(manager.cluster_connector.get_resource_allocation('disk') * 1000000)
allocated_gpus = manager.cluster_connector.get_resource_allocation('gpus')
print(f'\tCPU allocation: {allocated_cpus:.1f} CPUs allocated to tasks, {total_cpus:.1f} total')
print(f'\tMemory allocation: {allocated_mem} memory allocated to tasks, {total_mem} total')
print(f'\tDisk allocation: {allocated_disk} disk space allocated to tasks, {total_disk} total')
print(f'\tGPUs allocation: {allocated_gpus} GPUs allocated to tasks, {total_gpus} total')
示例13: display_stats
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def display_stats(filesize, started_on, ended_on=None):
ended_on = ended_on or now()
duration = (ended_on - started_on).total_seconds()
if humanfriendly:
hfilesize = humanfriendly.format_size(filesize, binary=True)
hduration = humanfriendly.format_timespan(duration, max_units=2)
speed = humanfriendly.format_size(filesize / duration)
msg = f"uploaded {hfilesize} in {hduration} ({speed}/s)"
else:
hfilesize = filesize / 2 ** 20 # size in MiB
speed = filesize / 1000000 / duration # MB/s
duration = duration / 60 # in mn
msg = f"uploaded {hfilesize:.3}MiB in {duration:.1}mn ({speed:.3}MBps)"
logger.info(f"[stats] {msg}")
示例14: format_size
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def format_size(value):
return humanfriendly.format_size(value, binary=True)
示例15: setupUi
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_size [as 别名]
def setupUi(self, MainWindow):
super().setupUi(MainWindow)
self.torrent = None
self.MainWindow = MainWindow
self.actionImportProfile.triggered.connect(self.import_profile)
self.actionExportProfile.triggered.connect(self.export_profile)
self.actionAbout.triggered.connect(self.showAboutDialog)
self.actionQuit.triggered.connect(self.MainWindow.close)
self.fileRadioButton.toggled.connect(self.inputModeToggle)
self.fileRadioButton.setChecked(True)
self.directoryRadioButton.toggled.connect(self.inputModeToggle)
self.browseButton.clicked.connect(self.browseInput)
self.batchModeCheckBox.stateChanged.connect(self.batchModeChanged)
self.inputEdit.dragEnterEvent = self.inputDragEnterEvent
self.inputEdit.dropEvent = self.inputDropEvent
self.pasteButton.clicked.connect(self.pasteInput)
self.pieceCountLabel.hide()
self.pieceSizeComboBox.addItem('Auto')
for x in PIECE_SIZES[1:]:
self.pieceSizeComboBox.addItem(
humanfriendly.format_size(x, binary=True))
self.pieceSizeComboBox.currentIndexChanged.connect(
self.pieceSizeChanged)
self.privateTorrentCheckBox.stateChanged.connect(
self.privateTorrentChanged)
self.commentEdit.textEdited.connect(
self.commentEdited)
self.sourceEdit.textEdited.connect(
self.sourceEdited)
self.md5CheckBox.stateChanged.connect(
self.md5Changed)
self.progressBar.hide()
self.createButton.setEnabled(False)
self.createButton.clicked.connect(self.createButtonClicked)
self.cancelButton.hide()
self.cancelButton.clicked.connect(self.cancel_creation)
self.resetButton.clicked.connect(self.reset)
self._statusBarMsg('Ready')