2017-04-16 64 views
0

我有用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脚本,对不同的呼叫nresult = 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!

+0

您应该能够按照示例中所示[覆盖运算符'new'](http://en.cppreference.com/w/cpp/memory/new/operator_new)并进行精确的测量。 – nwp

回答

0

memcheck是一个查找内存泄漏的工具,您应该使用massif (another tool available in valgrind)进行内存分配分析。

+0

它似乎是一个不错的选择,但有没有一种方法可以返回高峰内存消耗? – jsguy

+0

只是峰值内存消耗?这是任何过程监控实用程序可以显示给您的。如果您使用VS,那么您也可以使用内置内存监视器(主菜单 - >分析 - >性能分析器)。 – VTT

+0

谢谢,我会牢记这一点。我尝试过地块,说实话,尽管它很慢,但它提供了非常详细的内存消耗概述。在考虑你在评论中写下的内容后,我想我将不得不使用'/ usr/bin/time -v'和'最大驻留集大小(千字节)'变量来...... – jsguy

相关问题