我有用C++实现的算法A
和算法B
。理论上,A
使用的空间比B
多,实际情况也是这样。我想生成一些很好的图表来说明这一点。这两种算法接收输入n
,我想我的实验针对不同的n
变化,使图形的x轴必须是这样的n = 10^6, 2*10^6, ...
什么是在C++中运行内存使用算法的好方法?
通常,当涉及到如时间或高速缓存未命中的数据,我最首选的方法设置实验的过程如下。里面一个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
字符串只存储./algB
的输出,并完全忽略valgrind返回的内容。
谢谢你advace!
您应该能够按照示例中所示[覆盖运算符'new'](http://en.cppreference.com/w/cpp/memory/new/operator_new)并进行精确的测量。 – nwp