Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts

Sunday, January 28, 2018

Structure Padding in C/C++

這篇會簡單提到 C/C++ 裡面的struct padding.

前幾天面試有遇到相關問題, 沒有研究過 compiler 當場回答不出來

之後在網路上查了相關資料並且用clion測試後整理出結論:

structure 是 C/C++ 用來把不同data type 打包起來

struct car {
  int serial_number;
  long long year;
  char type;
  char name[8];
} car_t;

問題 1:  sizeof(car_t) 有多大呢?

這種問題,是半開放的問題

需要做很多假設

1. 第一件事一定要考慮 32/ 64 bit machines.
這個或許會影響 pointer size 的不同. 為什麼我說也許, 因為platform 也會影響 pointer size.

2. 第二件事是compiler,有些comiler 可以optimize. 我不太懂就不多贅述了

考慮完之後我們可以計算


  int serial_number; -> 32 bits -> 4 bytes
  long long year; -> 64 bits -> 8 bytes
  char type; -> 8 bits -> 1 byte;
  char name[8]; ->  8 * 8 bits -> 8 bytes

得到 4 + 8 + 1 + 8 = 21 bytes.

這並不是正確答案

在底層實作上會加上padding.

通常會找出struct 中最大的 bytes. 然後一個一個往下放進去

以上述例子

最大的element 是 8 bytes. 放不下的時候要補足8 bytes 再往下做

int serial_number; -> 4 bytes
#### padding 4 bytes
long long year; -> 8 bytes
#### padding 0 bytes
char type; -> 1 byte  +   char name[:7] -> 7 bytes
#### padding 0 bytes
char name[8:]; -> 1 byte
#### padding  7 bytes

最後總共會是32 bytes.

依照上述的規則如果我們把順序調整

struct car {
  int serial_number;
  char type; // change the order
  long long year;
  char name[8];
} car_t;

int serial_number; -> 4 bytes
char type; -> 1 byte
#### padding 3 bytes
long long year; -> 8 bytes
#### padding 0 bytes
char name[8]; -> 8 byte
#### padding 0 bytes

總共會用到 24 bytes

在底層C/C++ structure 非常常用

如果可以減少 size 也許會對performance有很大影響


https://www.ibm.com/developerworks/library/l-port64/index.html
https://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/







Monday, December 4, 2017

Dash Python API 中文簡介

這學期的雲端計算 project

用了 Dash 當作 front-end

這是 Dash 介紹

Written on top of Flask, Plotly.js, and React.js, Dash is ideal for building data visualization apps with highly custom user interfaces in pure Python. It's particularly suited for anyone who works with data in Python


整個架構需要寫一個 app.py

可以包含 plot graph 還有 html layout.

比較進階的寫法是 live updating components

這個 feature 可以設個 interval


讓網站在一個時間內自動update

這裡是簡單的example, 提供兩種寫 graph 的方法


https://gist.github.com/boalinlai/7da3aac5a73cd45e046c88bdaae016cf

layout 裡面用 id 去指定function

call back function 裡面要有 data, layout

然後設置一個 time interval

最後

指定完 host 還有 port 之後

sudo python app.py

ubuntu on x1c carbon 6 th

此篇網誌將會記錄 x1c 使用心得以及問題 @ 12/2018 拿到windows 10 pre-installed x1c 6th 壓縮容量 改bios開機設定 安裝 ubuntu 18 from usb @ issue 1. 電量問題 co...