在python中将浮点数列表打包成字节的最快方法 [英] Fastest way to pack a list of floats into bytes in python

查看:47
本文介绍了在python中将浮点数列表打包成字节的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 100k 个浮点数的列表,我想将其转换为字节缓冲区.

I have a list of say 100k floats and I want to convert it into a bytes buffer.

buf = bytes()
for val in floatList:
   buf += struct.pack('f', val)
return buf

这很慢.如何仅使用标准 Python 3.x 库使其更快.

This is quite slow. How can I make it faster using only standard Python 3.x libraries.

推荐答案

只要告诉 struct 你有多少 float 即可.在我慢速的笔记本电脑上,100k 浮点数大约需要 1/100 秒.

Just tell struct how many floats you have. 100k floats takes about a 1/100th of a second on my slow laptop.

import random
import struct

floatlist = [random.random() for _ in range(10**5)]
buf = struct.pack('%sf' % len(floatlist), *floatlist)

这篇关于在python中将浮点数列表打包成字节的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆