Just a disclaimer up front: this is a homework assignment; I come here because my (online) teach isn’t terribly responsive. That said, I think I have it all figured out except for one issue.
The assignment is to time how long it takes to create 1000 each of 3 arrays of 100000 size in different ways: Static, on the Stack, and on the Heap. I’m pretty sure I have the code right for creating the arrays. The problem I am running into is when I print avgTime to the screen, each function outputs the exact same value. So if the first function took 800ms, that time will just be repeated over for the next two functions. I think it has something to do with the scope of the avgTime variable. Any thoughts?
#include <iostream>
#include <windows.h>
using namespace std;
void fStaticArray() {
int i = 0;
DWORD avgTime;
while (i<1000){
DWORD before = GetTickCount();
static int staticArray [100000];
i++;
DWORD after = GetTickCount();
avgTime = avgTime + (after - before);
}
cout << "fStaticArray: " << (avgTime/1000) << "ms ";
//avgTime = 0;
}
void fStackArray() {
int i = 0;
DWORD avgTime;
while (i < 1000) {
DWORD before = GetTickCount();
int stackArray [100000];
i++;
DWORD after = GetTickCount();
avgTime = avgTime + (after - before);
}
cout << "fStackArray: " << (avgTime/1000) << "ms ";
}
void fHeapArray() {
int i = 0;
DWORD avgTime;
while (i < 1000) {
DWORD before = GetTickCount();
int * heapArray = new int[100000];
i++;
DWORD after = GetTickCount();
avgTime = avgTime + (after - before);
}
cout << "fHeapArray: " << (avgTime/1000) << "ms ";
}
int main(void) {
fStaticArray();
fStackArray();
fHeapArray();
}
There is no scope problem. Two things could make output same. First, they are same value. If they are and you are not convinced try putting different sleep in all loops or make them run for different numbers and you will see they print different. Second, they may be different, but as division of two int is int so they are printing same value. Try least one argument of division to float. Before going with any of two just try printing avgValue without division. Also you may want to put GetTickCount() before and after the while loop.