顯示具有 function 標籤的文章。 顯示所有文章
顯示具有 function 標籤的文章。 顯示所有文章

2019年11月16日 星期六

[C] 查看目前程式的記憶體用量 @ macOS 10.15

記得碩士生活很常被記憶體追殺,那時都是靠 unix tools 或是 /proc/ 查看指定的記憶體,都忘了其實是靠 process 自己去查詢資料,這次工作要協助 debug 抓資訊,就把它完成了:

#include <stdio.h>
#include <stdlib.h>

// Memory Usage
#include <sys/types.h>
#include <sys/sysctl.h>

void simple_wait() {
size_t wait_buf_size = 32;
char *wait_buf;
wait_buf = (char *)malloc(wait_buf_size * sizeof(char));
getline(&wait_buf, &wait_buf_size, stdin);
free(wait_buf);
}

void show_memory_usage() {
struct rusage usage;
printf("\n-- Memory Usage -- Begin --\n");

if(0 == getrusage(RUSAGE_SELF, &usage)) {
printf("\tBytes:\t%ld\n", usage.ru_maxrss);
printf("\t= \t%.3f KB\n", usage.ru_maxrss / 1024.0);
printf("\t= \t%.3f MB\n", usage.ru_maxrss / 1024.0 / 1024.0);
} else {
printf("\tREAD ERROR\n");
}

printf("-- End -- Memory Usage --\n");
}

int main(int argc, char *argv[]) {

show_memory_usage();
printf("press enter to continue\n");
simple_wait();

return 0;
}


用法:

$ gcc t.c
$ ./a.out

-- Memory Usage -- Begin --
Bytes: 671744
= 656.000 KB
= 0.641 MB
-- End -- Memory Usage --
press enter to continue


只是在 man page: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getrusage.2.html 的描述:

ru_maxrss    the maximum resident set size utilized (in kilobytes).

但看數據總覺得是 bytes 啊 XD 先記錄起來,有空再追蹤

2016年3月4日 星期五

Android 開發筆記 - 使用 Java Reflection 製作 Event Handler 流程控制

在 Android 上練習一些題目時,有碰到一連串 function call 的需求,特別是把每項工作做成 RISC 架構後,出現了重複使用的可能性,假設有 A, B, C, D 四個函式,有時任務是 A->B->D,有時是 B->C->A 的流程,這時就想找一個可以彈性設置任務流程的機制,有一點像 C/C++ 的 function pointer 或 virtual function 可以動態決定對象的機制,就隨意亂打關鍵字,想知道有沒可能得知 function name 後可以呼叫 function 做事,就找到 Java Reflection :http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html

於是乎,在 Java 環境中透過 ArrayList 記錄此次工作依序將執行的任務,每次挑一個出來用,就達成任務了 :P

紀錄一下(此例各個函式在此例沒有傳遞參數):

class Job {
private String tag = "Job";
private List<String> mFunctionNameList = new ArrayList<String>();

void callFunctions() {
if (mFunctionNameList.size() > 0) {
String methodName = mFunctionNameList.get(0);
mFunctionNameList.remove(0);
try {
Job.this.getClass().getDeclaredMethod(methodName).invoke(this);
} catch (Exception e) {
}
}
}

// call A -> C -> D
void task1() {
mFunctionNameList.clear();
mFunctionNameList.add("A");
mFunctionNameList.add("C");
mFunctionNameList.add("D");
callFunctions();
}

// call B -> C -> A
void task2() {
mFunctionNameList.clear();
mFunctionNameList.add("B");
mFunctionNameList.add("C");
mFunctionNameList.add("A");
callFunctions();
}

void A() {
Log.d(tag, "call A");
}
void B() {
Log.d(tag, "call B");
}
void C() {
Log.d(tag, "call C");
}
void D() {
Log.d(tag, "call D");
}
}