cpp_playground/misc/likely.cpp
wangjiacai f26a23b409
All checks were successful
continuous-integration/drone/push Build is passing
test how random/sorted dataset affect speed.
2023-02-12 14:59:21 +08:00

101 lines
2.6 KiB
C++

#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;
const int SIZE = 128 * 1024 * 1024;
const int RANGE = RAND_MAX / 2;
int arr[SIZE];
void func1(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))
big++;
else
small++;
}
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 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)
{
int big = 0, small = 0;
timeval start, end;
gettimeofday(&start, nullptr);
for (int idx = 0; idx < SIZE; idx++)
{
if (likely((pval[idx]) > RANGE / 2))
big++;
else
small++;
}
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_unlikely(int *pval)
{
int big = 0, small = 0;
timeval start, end;
gettimeofday(&start, nullptr);
for (int idx = 0; idx < SIZE; idx++)
{
if (unlikely((pval[idx]) > RANGE / 2))
big++;
else
small++;
}
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;
}
int main()
{
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;
func1(arr);
func2(arr);
func_likely(arr);
func_unlikely(arr);
}