/**************************************************************** **** **** This file belongs with the course **** Introduction to Scientific Programming in C++/Fortran2003 **** copyright 2016-2023 Victor Eijkhout eijkhout@tacc.utexas.edu **** **** heaptime.cxx : timing heap vs stack array **** ****************************************************************/ #include using std::cout; #include using std::function; #include using std::make_pair; using std::pair; #include using std::string; #include using std::vector; #include #define N 1000 double stacksum( double x ) { double array[N]; array[0] = x; for (int i=1; i arrayvector(N); double *array = arrayvector.data(); array[0] = x; for (int i=1; i& array ) { array[0] = x; for (int i=1; i heaparray(N); for ( auto array : { &(stackarray[0]),&(heaparray[0]) } ) { for (int a : { 1,2,3,4,6,8 } ) { size_t addr = (size_t) array; int p=2; for (int i=1; i > >{ {"local on stack",stacksum} , {"local on heap",heapsum} , {"local malloc",mallocsum} , {"global on stack", [&stackarray] (double x) -> double { return passstack(x,stackarray); } } , {"global on heap", [&heaparray] (double x) -> double { return passheap (x,heaparray ); } } , {"global malloc", [&mallocarray] (double x) -> double { return passmalloc (x,mallocarray ); } } } // end of vector of functions ) { auto start_time = myclock::now(); double s=0; for (int i=1; i<=NITER; ++i) { double x = i; s += sumfunction(x); } auto duration = myclock::now()-start_time; auto microsec_duration = std::chrono::duration_cast(duration); int usec = microsec_duration.count(); auto nanosec_duration = std::chrono::duration_cast(duration); float nsec_per_div = 1.*nanosec_duration.count()/NITER/N; printf("%15s: ",functionname.data()); printf("Sum = %e in %d usec",s,usec); //printf(", nsec/div %4.1f",nsec_per_div); printf(", cycles/div %4.1f", nsec_per_div*3.3 ); printf("\n"); } free(mallocarray); return 0; }