多版本函数
GNU C++ 编译器提供了一种“多版本函数”的机制,利用属性标签 __attribute__
可为不同的目标硬件架构编写不同版本的函数,运行时将自动根据当前平台切换使用。 多版本函数机制可以允许同一个函数在不同的目标扩展指令集下拥有多套不同的实现, 以充分利用特定扩展指令集的优势,加速程序运行。
目前,GCC 编译器原生支持 X86 平台下的多版本函数机制,ARM 正致力于 为 AArch64 架构引入该机制的支持。
__attribute__ ((target ("default")))
int foo(void) {
// 默认版本的 foo 函数
return 0;
}
__attribute__ ((target ("sse4.2")))
int foo(void) {
// 针对 SSE 4.2 架构的 foo 函数
return 1;
}
__attribute__ ((target ("arch=atom")))
int foo(void) {
// 针对 Atom 系列处理器的 foo 函数
return 2;
}
__attribute__ ((target ("arch=amdfam10")))
int foo(void) {
// 针对 0x10 系列 AMD 处理器的 foo 函数
return 3;
}
int main () {
// 自动根据目标硬件架构平台调用对应版本的 foo 函数
printf("%d", foo());
return 0;
}