顯示具有 glib 標籤的文章。 顯示所有文章
顯示具有 glib 標籤的文章。 顯示所有文章

2017年9月14日 星期四

[轉] 內核的likely()/unlikely和glib的G_LIKELY/G_UNLIKELY

內核中的 likely() 與 unlikely()


在 2.6 內核中,隨處可以見到 likely() 和 unlikely() 的身影,那麼為什麼要用它們?它們之間有什麼區別?

 
首先要明確:
if(likely(value)) 等價於 if(value)
if(unlikely(value)) 也等價於 if(value)
也就是說 likely() 和 unlikely() 從閱讀和理解代碼的角度來看,是一樣的!!!

這兩個宏在內核中定義如下:

 
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)


__builtin_expect() 是 GCC (version >= 2.96)提供給程序員使用的,目的是將「分支轉移」的信息提供給編譯器,這樣編譯器可以對代碼進行優化,以減少指令跳轉帶來的性能下降。

__builtin_expect((x),1) 表示 x 的值為真的可能性更大;
__builtin_expect((x),0) 表示 x 的值為假的可能性更大。

也就是說,使用 likely() ,執行 if 後面的語句 的機會更大,使用unlikely(),執行else 後面的語句的機會更大。
例如下面這段代碼,作者就認為 prev 不等於 next 的可能性更大,

 
if (likely(prev != next)) {
next->timestamp = now;
...
} else {
...;
}

通過這種方式,編譯器在編譯過程中,會將可能性更大的代碼緊跟著起面的代碼,從而減少指令跳轉帶來的性能上的下降。


下面以兩個例子來加深這種理解:

第一個例子: example1.c

 
int testfun(int x)
{
if(__builtin_expect(x, 0)) {
^^^--- We instruct the compiler, "else" block is more probable
x = 5;
x = x * x;
} else {
x = 6;
}
return x;
}

在這個例子中,我們認為 x 為0的可能性更大

編譯以後,通過 objdump 來觀察彙編指令,在我的 2.4 內核機器上,結果如下:

# gcc -O2 -c example1.c
# objdump -d example1.o

 
Disassembly of section .text:

00000000 <testfun>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 45 08 mov 0x8(%ebp),%eax
6: 85 c0 test %eax,%eax
8: 75 07 jne 11 <testfun+0x11>
a: b8 06 00 00 00 mov $0x6,%eax
f: c9 leave
10: c3 ret
11: b8 19 00 00 00 mov $0x19,%eax
16: eb f7 jmp f <testfun+0xf>


可以看到,編譯器使用的是 jne (不相等跳轉)指令,並且 else block 中的代碼緊跟在後面。

8: 75 07 jne 11 <testfun+0x11>
a: b8 06 00 00 00 mov $0x6,%eax


第二個例子: example2.c


 
int testfun(int x)
{
if(__builtin_expect(x, 1)) {
^^^ --- We instruct the compiler, "if" block is more probable
x = 5;
x = x * x;
} else {
x = 6;
}
return x;
}

在這個例子中,我們認為 x 不為 0 的可能性更大

編譯以後,通過 objdump 來觀察彙編指令,在我的 2.4 內核機器上,結果如下:

# gcc -O2 -c example2.c
# objdump -d example2.o


 
Disassembly of section .text:

00000000 <testfun>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 45 08 mov 0x8(%ebp),%eax
6: 85 c0 test %eax,%eax
8: 74 07 je 11 <testfun+0x11>
a: b8 19 00 00 00 mov $0x19,%eax
f: c9 leave
10: c3 ret
11: b8 06 00 00 00 mov $0x6,%eax
16: eb f7 jmp f <testfun+0xf>


這次編譯器使用的是 je (相等跳轉)指令,並且 if block 中的代碼緊跟在後面。

8: 74 07 je 11 <testfun+0x11>
a: b8 19 00 00 00 mov $0x19,%eax

G_LIKELY和G_UNLIKELY

在GTK+2.0源碼中有很多這樣的宏:G_LIKELY和G_UNLIKELY。比如下面這段代碼:
if (G_LIKELY (acat == 1))       /* allocate through magazine layer */
      {
        ThreadMemory *tmem = thread_memory_from_self();
        guint ix = SLAB_INDEX (allocator, chunk_size);
        if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
          {
            thread_memory_swap_magazines (tmem, ix);
            if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))
              thread_memory_magazine1_reload (tmem, ix);
          }
        mem = thread_memory_magazine1_alloc (tmem, ix);
      }
在源碼中,宏G_LIKELY和G_UNLIKELY 是這麼定義的:
#define G_LIKELY(expr) (__builtin_expect (_G_BOOLEAN_EXPR(expr), 1))
  #define G_UNLIKELY(expr) (__builtin_expect (_G_BOOLEAN_EXPR(expr), 0))
宏_G_BOOLEAN_EXPR的作用是把expr轉換為0和1,即真假兩種。要理解宏G_LIKELY和G_UNLIKELY ,很明顯必須理解__builtin_expect。__builtin_expect是GCC(version>=2.9)引進的宏,其作用就是幫助編譯器判斷條件跳轉的預期值,避免跳轉造成時間亂費。拿上面的代碼來說:
if (G_LIKELY (acat == 1)) //表示大多數情況下if裡面是真,程序大多數直接執行if裡面的程序
if (G_UNLIKELY (thread_memory_magazine1_is_empty (tmem, ix)))//表示大多數情況if裡面為假,程序大多數直接執行else裡面的程序
可能大家看到還是一頭霧水,看下面一段就會明白其中的樂趣啦;
//test_builtin_expect.c 
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
int test_likely(int x)
{
 if(LIKELY(x))
 {
    x = 5;
 }
 else
 {
    x = 6;
 }
  
 return x;
}
int test_unlikely(int x)
{
 if(UNLIKELY(x))
 {
    x = 5;
 }
 else
 {
    x = 6;
 }
  
 return x;
}
[lammy@localhost test_builtin_expect]$ gcc -fprofile-arcs -O2 -c test_builtin_expect.c 
[lammy@localhost test_builtin_expect]$ objdump -d test_builtin_expect.o
test_builtin_expect.o:       file format elf32-i386
Disassembly of section .text:
00000000 <test_likely>:
     0: 55                      push     %ebp
     1: 89 e5                   mov      %esp,%ebp
     3: 8b 45 08                mov      0x8(%ebp),%eax
     6: 83 05 38 00 00 00 01  addl     $0x1,0x38
     d: 83 15 3c 00 00 00 00  adcl     $0x0,0x3c
  14: 85 c0                   test     %eax,%eax
  16: 74 15                   je       2d <test_likely+0x2d>//主要看這裡
  18: 83 05 40 00 00 00 01  addl     $0x1,0x40
  1f: b8 05 00 00 00          mov      $0x5,%eax
  24: 83 15 44 00 00 00 00  adcl     $0x0,0x44
  2b: 5d                      pop      %ebp
  2c: c3                      ret      
  2d: 83 05 48 00 00 00 01  addl     $0x1,0x48
  34: b8 06 00 00 00          mov      $0x6,%eax
  39: 83 15 4c 00 00 00 00  adcl     $0x0,0x4c
  40: 5d                      pop      %ebp
  41: c3                      ret      
  42: 8d b4 26 00 00 00 00  lea      0x0(%esi,%eiz,1),%esi
  49: 8d bc 27 00 00 00 00  lea      0x0(%edi,%eiz,1),%edi
00000050 <test_unlikely>:
  50: 55                      push     %ebp
  51: 89 e5                   mov      %esp,%ebp
  53: 8b 55 08                mov      0x8(%ebp),%edx
  56: 83 05 20 00 00 00 01  addl     $0x1,0x20
  5d: 83 15 24 00 00 00 00  adcl     $0x0,0x24
  64: 85 d2                   test     %edx,%edx
  66: 75 15                   jne      7d <test_unlikely+0x2d>//主要看這裡
  68: 83 05 30 00 00 00 01  addl     $0x1,0x30
  6f: b8 06 00 00 00          mov      $0x6,%eax
  74: 83 15 34 00 00 00 00  adcl     $0x0,0x34
  7b: 5d                      pop      %ebp
  7c: c3                      ret      
  7d: 83 05 28 00 00 00 01  addl     $0x1,0x28
  84: b8 05 00 00 00          mov      $0x5,%eax
  89: 83 15 2c 00 00 00 00  adcl     $0x0,0x2c
  90: 5d                      pop      %ebp
  91: c3                      ret      
  92: 8d b4 26 00 00 00 00  lea      0x0(%esi,%eiz,1),%esi
  99: 8d bc 27 00 00 00 00  lea      0x0(%edi,%eiz,1),%edi
000000a0 <_GLOBAL__I_65535_0_test_likely>:
  a0: 55                      push     %ebp
  a1: 89 e5                   mov      %esp,%ebp
  a3: 83 ec 08                sub 

2017年9月13日 星期三

GObject的物件屬性

https://imtx.me/archives/186.html

9GObject的物件屬性
Feb 25, 2008
GObject既然是物件,肯定有屬性。既然有屬性,肯定有獲取和設置的辦法。GObject在這方面非常靈活,除具備一般物件導向程式的共性外,GObject的批量設置屬性的方法非常不錯。
-----
GObject的其中一個漂亮特性就是它那為物件屬性準備的通用get/set機制。當一個物件被產生實體以後,物件的類初始化處理將用g_object_class_install_property來註冊物件的屬性(由gobject.c中實現)。
理解物件屬性是如何工作的最好就是看下面的例子:
/************************************************/
/* Implementation                               */
/************************************************/
enum {
MAMAN_BAR_CONSTRUCT_NAME = 1,
MAMAN_BAR_PAPA_NUMBER,
};

static void
maman_bar_instance_init (GTypeInstance   *instance,
gpointer         g_class)
{
MamanBar *self = (MamanBar *)instance;
}

static void
maman_bar_set_property (GObject      *object,
guint         property_id,
const GValue *value,
GParamSpec   *pspec)
{
MamanBar *self = (MamanBar *) object;
switch (property_id) {
case MAMAN_BAR_CONSTRUCT_NAME: {
g_free (self->priv->name);
self->priv->name = g_value_dup_string (value);
g_print ("maman: %s\n",self->priv->name);
}
break;
case MAMAN_BAR_PAPA_NUMBER: {
self->priv->papa_number = g_value_get_uchar (value);
g_print ("papa: %u\n",self->priv->papa_number);
}
break;
default:
/* We don't have any other property... */
G_OBJECT_WARN_INVALID_PROPERTY_ID(object,property_id,pspec);
break;
}
}

static void
maman_bar_get_property (GObject      *object,
guint         property_id,
GValue       *value,
GParamSpec   *pspec)
{
MamanBar *self = (MamanBar *) object;
switch (property_id) {
case MAMAN_BAR_CONSTRUCT_NAME: {
g_value_set_string (value, self->priv->name);
}
break;
case MAMAN_BAR_PAPA_NUMBER: {
g_value_set_uchar (value, self->priv->papa_number);
}
break;
default:
/* We don't have any other property... */
G_OBJECT_WARN_INVALID_PROPERTY_ID(object,property_id,pspec);
break;
}
}

static void
maman_bar_class_init (gpointer g_class,
gpointer g_class_data)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
MamanBarClass *klass = MAMAN_BAR_CLASS (g_class);
GParamSpec *pspec;
gobject_class->set_property = maman_bar_set_property;
gobject_class->get_property = maman_bar_get_property;
pspec = g_param_spec_string ("maman-name",
"Maman construct prop",
"Set maman's name",
"no-name-set" /* default value */,
G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
g_object_class_install_property (gobject_class,
MAMAN_BAR_CONSTRUCT_NAME,
pspec);
pspec = g_param_spec_uchar ("papa-number",
"Number of current Papa",
"Set/Get papa's number",
0  /* minimum value */,
10 /* maximum value */,
2  /* default value */,
G_PARAM_READWRITE);
g_object_class_install_property (gobject_class,
MAMAN_BAR_PAPA_NUMBER,
pspec);
}

/************************************************/
/* Use                                          */
/************************************************/
GObject *bar;
GValue val = {0,};
bar = g_object_new (MAMAN_TYPE_SUBBAR, NULL);
g_value_init (&val, G_TYPE_CHAR);
g_value_set_char (&val, 11);
g_object_set_property (G_OBJECT (bar), "papa-number", &val);
上面的例子看起來應該是簡單的,但是很多事情發生了:
g_object_set_property先確保相應名稱的屬性已經在barclass_init處理函數中被註冊。如果是的話,它依次調用類繼承關係中的object_set_property,從底至頂,基礎類型用來找到註冊了這個屬性的類。接著它嘗試轉換使用者提供的GValue到屬性所關聯的GValue
如果使用者提供了一個有符號的字元GValue,就像這裡所示,如果物件的屬性被註冊為一個無符號的整型,g_value_transform將會試著轉換輸入的有符號的字元到一個無符號的整型。當然,轉換是否成功取取決於可用的轉換函數。實際上,如果需要的時候,總會有相關的轉換函數可以用。
在轉型以後,GValue將被g_param_value_validata來驗證,以確保使用者保存在GValue中的資料吻合由屬性的GParamSpea所描述的字元特性。在這裡,我們在class_init裡提供的GParamSpec有一個驗證函數來確保GValue包含了一個代表最小和最大邊界的GParamSpec。在上面的例子中,用戶端的GValue並沒有尊重規範(它設置為了11,而最大值是10)。因為這樣,所了g_object_set_property函數將返回一個錯誤。
如果用戶的GValue已經被設置成了一個可用的值,g_object_set_property將處理一下呼叫至物件的set_property的類方法。在這裡,因為我們在Foo的實現代碼中並沒有重載這個函數,代碼路徑將會跳到foo_set_property在收到g_object_class_install_property存儲了GParamSpecparam_id後。
一時已經用物件的set_property類方法來設置好屬性以後,代碼路徑將調用g_object_nofity_queue_thaw使返回到g_object_set_property 。這個函數確保“notify”信號已經在物件實例完成改變屬性後被發出,除非通知台已經被g_object_free_notify所凍潔。
g_object_thaw_nofity可以被用來重新啟用通過“notify”信號的屬性修改的通知中心。這是非常重要的,記住當屬性被改變時通知中心是否被凍結,“notify”信號將會當在屬性改變的一睡意由通知中心所發出:沒有屬性改變會因“notify”所信號。只有通過通知中心的凍結機制才能使信號發身被延誤。
這聽起來像是一個無聊的任務每次設置GValues當我想需要一個屬性時。實際上我們僅僅很少這樣做。g_object_set_propertyg_object_get_property一般是用來語言綁定的。對應用程式來說,有一個更簡單的方法,在下面描述。
同時修改多個屬性
我想這很有趣,我們可以通過g_object_setg_object_set_valist函數來同時設置多個屬性值。用戶端代碼可以被重寫為:
MamanBar *foo;
foo = /* */;
g_object_set (G_OBJECT (foo),
"papa-number", 2,
"maman-name", "test",
NULL);
這個節省了我們管理用g_object_set_property來處理GValue的時間。在被修改時這個代碼同樣會觸發每個屬性。
當然,_get的版本同樣是存在的:g_object_getg_object-get_valist可以用來一次性得到很多屬性。
這些高級的方法有一個缺點──它們不提供一個返回值。在使用它們時,你需要注意這些參數類型和範圍 。(暫時不會了)
These high level functions have one drawback - they don't provide a return result. One should pay attention to the argument types and ranges when using them. A know source of errors is to e.g. pass a gfloat instead of a gdouble and thus shifting all subsequent parameters by four bytes. Also forgetting the terminating NULL will lead to unexpected behaviour.
如果你認真看這章的話,現在你應該已經知道了g_object_newg_object_newvg_object_new_valist是如何工作的:它們解析使用者提供的變數數目和參數並當物件成功的創建以後,用這些參數調用g_object_set。當然,“notify”信號同樣會在每個屬性改變後發射。

GObject 學習筆記彙總

GObject 學習筆記彙總---1
http://blog.csdn.net/yanbixing123/article/details/52848940

GObject 學習筆記彙總---2
http://blog.csdn.net/yanbixing123/article/details/52848953

GObject 學習筆記彙總---3
http://blog.csdn.net/yanbixing123/article/details/52849049

GObject 學習筆記彙總---4
http://blog.csdn.net/yanbixing123/article/details/52849099

GObject 學習筆記彙總---5
http://blog.csdn.net/yanbixing123/article/details/52849215

GObject 學習筆記彙總---6
http://blog.csdn.net/yanbixing123/article/details/52849312

GObject 學習筆記彙總---7
http://blog.csdn.net/yanbixing123/article/details/52849372

GObject 學習筆記彙總---8
http://blog.csdn.net/yanbixing123/article/details/52849423

GObject 學習筆記彙總---9
http://blog.csdn.net/yanbixing123/article/details/52849483

GObject 學習筆記彙總---10
http://blog.csdn.net/yanbixing123/article/details/52849560

GObject 學習筆記彙總---11
http://blog.csdn.net/yanbixing123/article/details/52849605

GObject 學習筆記彙總---12
http://blog.csdn.net/yanbixing123/article/details/52849743

GObject 學習筆記彙總---13
http://blog.csdn.net/yanbixing123/article/details/52851822

GObject 學習筆記彙總---14
http://blog.csdn.net/yanbixing123/article/details/52851841

GObject 學習筆記彙總---15
http://blog.csdn.net/yanbixing123/article/details/52851851

GObject入門

http://www.wl-chuang.com/blog/categories/gobject/