add cpu caching tester.
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
wangjiacai 2023-02-12 00:17:09 +08:00
parent 5f339eaa55
commit e6dfd24678
2 changed files with 79 additions and 23 deletions

View File

@ -21,4 +21,7 @@ steps:
- cd misc || exit - cd misc || exit
- g++ sizeof.cpp -o sizeof && ./sizeof - g++ sizeof.cpp -o sizeof && ./sizeof
- g++ caching.cpp -o caching && ./caching
- echo "following program fails to show the effect of 'likely' due to CPU branch predictor."
- g++ likely.cpp -o likely && ./likely
- cd - - cd -

53
misc/caching.cpp Normal file
View File

@ -0,0 +1,53 @@
#include <iostream>
#include <sys/time.h>
#include <random>
using namespace std;
const int SIZE = 256 * 1024 * 1024;
const int pagenum = 16 * 1024;
const int pagesize = SIZE / pagenum;
void xorsum_seq(int *data)
{
int xorsum = 0;
timeval start, end;
gettimeofday(&start, nullptr);
for (int page = 0; page < pagenum; page++)
{
for (int idx = 0; idx < pagesize; idx++)
xorsum ^= data[page * pagesize + idx];
}
gettimeofday(&end, nullptr);
double usec = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000;
cout << __func__ << " duration: " << usec << ", xorsum: " << xorsum << endl;
}
void xorsum_jmp(int *data)
{
int xorsum = 0;
timeval start, end;
gettimeofday(&start, nullptr);
for (int idx = 0; idx < pagesize; idx++)
{
for (int page = 0; page < pagenum; page++)
xorsum ^= data[page * pagesize + idx];
}
gettimeofday(&end, nullptr);
double usec = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000;
cout << __func__ << " duration: " << usec << ", xorsum: " << xorsum << endl;
}
int main()
{
int *data = new int[SIZE];
int xorsum = 0;
srand(time(nullptr));
for (int idx = 0; idx < SIZE; idx++)
{
data[idx] = rand();
}
xorsum_seq(data);
xorsum_jmp(data);
}