很长一段时间以来,编译器已经可以生成优化的二进制程序。然而,时至今日,要确切地知道对特定的程序应该选择什么样的优化,以及这些优化是否有利于优化程序,依然是困难而令人沮丧的。在这个简单的教程中,我们将探讨一个简单的例子,以介绍一些基本的优化和AutoFDO。
以如下的冒泡排序程序为例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#define ARRAY_LEN 30000
static struct timeval tm1;
static inline void start() {
gettimeofday(&tm1, NULL);
}
static inline void stop() {
struct timeval tm2;
gettimeofday(&tm2, NULL);
unsigned long long t = 1000 * (tm2.tv_sec - tm1.tv_sec) +\
(tm2.tv_usec - tm1.tv_usec) / 1000;
printf("%llu ms\n", t);
}
void bubble_sort (int *a, int n) {
int i, t, s = 1;
while (s) {
s = 0;
for (i = 1; i < n; i++) {
if (a[i] < a[i - 1]) {
t = a[i];
a[i] = a[i - 1];
a[i - 1] = t;