簡體   English   中英

在C ++中對算法的內存使用情況進行實驗的一種好方法是什么?

[英]what is a good way to run experiments for the memory usage of an algorithm in C++?

我有用C ++實現的算法A和算法B 理論上, AB使用更多的空間,事實證明,在實踐中也是如此。 我想生成一些漂亮的圖形來說明這一點。 兩種算法都接收輸入n ,我希望我的實驗針對不同的n進行變化,因此圖的x軸必須​​類似n = 10^6, 2*10^6, ...

通常,當涉及到時間或緩存丟失之類的數據時,我最喜歡的實驗設置方法如下。 在C ++文件中,我具有如下實現的算法:

#include <iostream>
using namespace std;
int counters[1000];
void init_statistics(){
   //use some library for example papi (http://icl.cs.utk.edu/papi/software/)
  //to start counting, store the results in the counters array
}

void stop_statistics(){
   //this is just to stop counting
}
int algA(int n){
//algorithm code
int result = ...
return result;
}

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

   int n = atoi(argv[1]);
   init_statistics(); //function that initializes the statistic counters
   int res = algA(n);
   end_statistics(); //function that ends the statistics counters
   cout<<res<<counter[0]<<counter[1]<<....<<endl;

}

然后,我將創建一個python腳本,用於不同的n調用result = subprocess.check_output(['./algB',...]) 之后,用python解析結果字符串並以適當的格式打印。 例如,如果將R用於繪圖,則可以將數據打印到外部文件中,其中每個計數器用\\t分隔。

這對我來說效果很好,但是現在是我第一次需要有關算法使用的空間的數據,而且我不確定如何計算該空間。 一種方法是使用valgrind,這是valgrind可能的輸出:

==15447== Memcheck, a memory error detector
==15447== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==15447== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==15447== Command: ./algB 1.txt 2.txt
==15447== 
==15447== 
==15447== HEAP SUMMARY:
==15447==     in use at exit: 72,704 bytes in 1 blocks
==15447==   total heap usage: 39 allocs, 38 frees, 471,174,306 bytes allocated
==15447== 
==15447== LEAK SUMMARY:
==15447==    definitely lost: 0 bytes in 0 blocks
==15447==    indirectly lost: 0 bytes in 0 blocks
==15447==      possibly lost: 0 bytes in 0 blocks
==15447==    still reachable: 72,704 bytes in 1 blocks
==15447==         suppressed: 0 bytes in 0 blocks
==15447== Rerun with --leak-check=full to see details of leaked memory
==15447== 
==15447== For counts of detected and suppressed errors, rerun with: -v
==15447== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

有趣的數字是471,174,306 bytes 但是,valgrind大大減慢了執行時間,同時,不僅返回此數字,而且返回了這個大字符串。 而且我不確定如何解析它,因為由於某種原因,如果使用python我調用result = subprocess.check_output(['valgrind','./algB',...]) ,則result字符串僅存儲by的輸出./algB並且完全忽略valgrind返回的內容。

謝謝你的放心!

memcheck是用於發現內存泄漏的工具,您應該使用massif (valgrind中的另一種工具)進行內存分配分析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM