Skip to content

Instantly share code, notes, and snippets.

@Noppy
Last active May 17, 2020 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Noppy/9bc1f9f7ab2a4ec4d3ae83f6b734aa35 to your computer and use it in GitHub Desktop.
Save Noppy/9bc1f9f7ab2a4ec4d3ae83f6b734aa35 to your computer and use it in GitHub Desktop.
Verifying on Memory behavior
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#define LENGTH (64UL*1024*1024)
#define INTERVAL 10
void print_time(char *buf){
struct timespec ts;
struct tm tm;
clock_gettime(CLOCK_REALTIME, &ts);
localtime_r( &ts.tv_sec, &tm);
printf("%d/%02d/%02d %02d:%02d:%02d.%06ld: %s\n",
tm.tm_year+1900,
tm.tm_mon+1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
ts.tv_nsec/1000,
buf);
return;
}
static void check_bytes(unsigned long *addr)
{
printf("First hex is %x\n", *((unsigned long *)addr));
}
static void write_bytes(unsigned long *addr)
{
unsigned long i,count,point;
point = LENGTH / 20;
count = 0;
for (i = 0; i < LENGTH; i++){
*(addr + i) = (unsigned long)i;
//printf("i=%10lu \n",i);
count++;
if( count >= point ){
sleep(1);
count=0;
}
}
return;
}
static int read_bytes(unsigned long *addr)
{
unsigned long i,count,point,dummy;
point = LENGTH / 20;
count = 0;
check_bytes(addr);
for (i = 0; i < LENGTH; i++){
dummy = (unsigned long)*(addr + i);
//printf("i=%10lu dummy=%10lu\n",i, dummy);
count++;
if( count >= point ){
sleep(1);
count=0;
}
}
return 0;
}
int main(void)
{
unsigned long *addr;
int ret;
print_time("upped the test program");
sleep(INTERVAL);
print_time("step1 get virtual memory via malloc");
addr = malloc(LENGTH * sizeof(unsigned long) );
if (addr == NULL ) {
perror("malloc");
exit(1);
}
printf("Returned address is %p\n", addr);
check_bytes(addr);
sleep(INTERVAL);
print_time("step2 start reading");
ret = read_bytes(addr);
print_time("step2 finish reading");
sleep(INTERVAL);
print_time("step3 start writing");
write_bytes(addr);
print_time("step3 finish writing");
sleep(INTERVAL);
print_time("step4 start reading");
ret = read_bytes(addr);
print_time("step4 finish reading");
/* munmap() length of MAP_HUGETLB memory must be hugepage aligned */
sleep(INTERVAL);
print_time("step5 free");
free(addr);
sleep(INTERVAL);
print_time("quit the test promgram");
return ret;
}
@Noppy
Copy link
Author

Noppy commented May 17, 2020

Pasear,
Thanks for your advice.
I have also confirmed that read_bytes function does not read too.
Therefore, I fixed the program.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment