cpp_playground/misc/likely.cpp

101 lines
2.6 KiB
C++
Raw Permalink Normal View History

#include <algorithm>
#include <iostream>
#include <sys/time.h>
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
using namespace std;
2023-02-12 00:15:06 +08:00
const int SIZE = 128 * 1024 * 1024;
const int RANGE = RAND_MAX / 2;
int arr[SIZE];
2023-02-12 00:15:06 +08:00
void func1(int *pval)
{
2023-02-12 00:15:06 +08:00
int big = 0, small = 0;
timeval start, end;
gettimeofday(&start, nullptr);
2023-02-12 00:15:06 +08:00
for (int idx = 0; idx < SIZE; idx++)
{
2023-02-12 00:15:06 +08:00
if (((pval[idx]) > RANGE / 2))
big++;
else
2023-02-12 00:15:06 +08:00
small++;
}
gettimeofday(&end, nullptr);
double usec = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000;
2023-02-12 00:15:06 +08:00
cout << __func__ << " duration: " << usec << ", big: " << big << ", small:" << small << endl;
}
void func2(int *pval)
{
int big = 0, small = 0;
timeval start, end;
gettimeofday(&start, nullptr);
for (int idx = 0; idx < SIZE; idx++)
{
if (((pval[idx]) <= RANGE / 2))
small++;
else
big++;
}
gettimeofday(&end, nullptr);
double usec = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000;
cout << __func__ << " duration: " << usec << ", big: " << big << ", small:" << small << endl;
}
void func_likely(int *pval)
{
2023-02-12 00:15:06 +08:00
int big = 0, small = 0;
timeval start, end;
gettimeofday(&start, nullptr);
2023-02-12 00:15:06 +08:00
for (int idx = 0; idx < SIZE; idx++)
{
2023-02-12 00:15:06 +08:00
if (likely((pval[idx]) > RANGE / 2))
big++;
else
2023-02-12 00:15:06 +08:00
small++;
}
gettimeofday(&end, nullptr);
double usec = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000;
2023-02-12 00:15:06 +08:00
cout << __func__ << " duration: " << usec << ", big: " << big << ", small:" << small << endl;
}
void func_unlikely(int *pval)
{
2023-02-12 00:15:06 +08:00
int big = 0, small = 0;
timeval start, end;
gettimeofday(&start, nullptr);
2023-02-12 00:15:06 +08:00
for (int idx = 0; idx < SIZE; idx++)
{
2023-02-12 00:15:06 +08:00
if (unlikely((pval[idx]) > RANGE / 2))
big++;
else
2023-02-12 00:15:06 +08:00
small++;
}
2023-02-12 00:15:06 +08:00
gettimeofday(&end, nullptr);
double usec = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000;
2023-02-12 00:15:06 +08:00
cout << __func__ << " duration: " << usec << ", big: " << big << ", small:" << small << endl;
}
int main()
{
2023-02-12 00:15:06 +08:00
srand(time(nullptr));
for (int i = 0; i < SIZE; i++)
{
arr[i] = (rand() % (RANGE + 1));
}
cout << "random dataset:" << endl;
func1(arr);
func2(arr);
func_likely(arr);
func_unlikely(arr);
sort(arr, arr + SIZE);
cout << "sorted dataset:" << endl;
2023-02-12 00:15:06 +08:00
func1(arr);
func2(arr);
func_likely(arr);
func_unlikely(arr);
}