93 lines
2.4 KiB
C++
93 lines
2.4 KiB
C++
#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)) + 0.499 * RANGE;
|
|
}
|
|
func1(arr);
|
|
func2(arr);
|
|
func_likely(arr);
|
|
func_unlikely(arr);
|
|
} |