隨着嵌入式C派遣了很多數字,我想以減少傳輸時間,
爲了提高時間性能,您可以發送和/或接收的多個號碼一次。在我的測試中,array.fromfile()
比struct.unpack()
快10 - 100倍。它的代價是調用array.byteswap()
有時會明確考慮到字節順序。
如果C程序和Python腳本在相同機器(相同的大小,相同的字節順序)上運行;那麼您可以使用fwrite
將短整數寫爲C端的平臺值,並使用array.fromfile()
on Python side以原生格式讀取它們。
例如,打印短整型二進制:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
short a[] = {31415, 9265, 3589, 793};
size_t n = sizeof a/sizeof *a;
if (fwrite(&n, sizeof n, 1, stdout) != 1) exit(EXIT_FAILURE); /* send size */
return (fwrite(a, sizeof *a, n, stdout) < n) ? EXIT_FAILURE : EXIT_SUCCESS;
}
讀它在Python:
#!/usr/bin/env python3
import sys
import array
import struct
# make stdin binary
file = sys.stdin.detach()
# read size
size_format = 'N' # size_t
n, = struct.unpack(size_format, file.read(struct.calcsize(size_format)))
print(n)
a = array.array('h') # native short int
a.fromfile(file, n)
print(a.tolist()) # -> [31415, 9265, 3589, 793]
array.fromfile
應該是有效的時間和存儲器,明智的。如果您不知道尺寸,請致電a.fromfile
,直到EOFError
被引發。
如果C程序和Python腳本是在不同的機器,那麼你可以在網絡字節順序發送整數:
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h> /* htons() */
int main(void) {
short a[] = {31415, 9265, 3589, 793};
/* print one integer at a time */
short *p = a, *end = &a[sizeof a/sizeof *a];
for (; p != end; ++p) {
uint16_t s = htons(*p); /* convert from native to network byte order */
if (fwrite(&s, sizeof s, 1, stdout) != 1) exit(EXIT_FAILURE);
}
return 0;
}
並交換字節順序如果在Python端必要的:
#!/usr/bin/env python
import array
import sys
a = array.array('h') # short int in native byte order, byte swap might be needed
for i in range(15, 128):
try: # double size to avoid O(n**2) behaviour
a.fromfile(sys.stdin, 2 << i)
except EOFError:
break
if sys.byteorder != 'big': # if not network order
a.byteswap() # swap byte order
print(a.tolist()) # -> [31415, 9265, 3589, 793]
爲避免轉換爲網絡訂單,您可以改爲發送幻數。它允許在Python派在C面的本機字節順序編號(如在第一代碼示例),並檢查它來交換字節,如果必要的:
MAGIC = 1
if a[0] != MAGIC:
a.byteswap()
if a[0] != MAGIC:
raise ValueError("Unexpected %d" % a[0])