// Rather simple C++ time test. // Builds and sorts array(s) of numbers, // using C++ that is not terribly general // and is rather low-level, really rather C-ish. // (Version for Microsoft Visual C++.) #include #include // Builds a "list" (actually a dynamically allocated array) of ints. int *make_int_array(int nHowMany) { int *pnMyList = (int *) malloc(sizeof(int) * nHowMany); if (pnMyList == NULL) { printf("Failed to allocate memory for ints list.\n"); } int *pnWhere = pnMyList; // Where we are storing int. long int i = 20; long int j = 245; long int k = 8003; while (nHowMany--) { *(pnWhere++) = ( (i % 20) + (j * 4023 % 145) + (k * 5671 % 879) ); ++i; ++j; ++k; } return pnMyList; } // int *make_int_array(int) // Stores a time (in milliseconds since Windows started) into array. // Marks position after valid time with 0 value. void add_a_time(DWORD *pdwTimes) { while (*pdwTimes) ++pdwTimes; *pdwTimes = GetTickCount(); *(pdwTimes + 1) = 0; // Marks end of valid times. } // void add_a_time(DWORD adwTimes[]) // Prints valid times in times array (values from GetTickCount(), terminated with 0.) void print_times(DWORD *pdwTimes) { while (*pdwTimes) { printf("%f secs, ", ((float) *pdwTimes) / 1000); ++pdwTimes; } printf("(end)\n"); } // void print_times(DWORD adwTimes[]) void print_ints(int *pn, int nHowMany) { while (nHowMany) { printf("%d", *(pn++)); if (--nHowMany) printf(", "); } printf("\n"); } // void print_ints(int *pn, int nHowMany) int compare_for_qsort( const void *arg1, const void *arg2 ) { int n1 = *( (int *) arg1); // Circumlocutions like this are one ... int n2 = *( (int *) arg2); // "benefit" of a strongly typed language? return n1 - n2; // Quick-n-easy hack, faster than the more methodical code below. /* if (n1 < n2) return -1; if (n1 == n2) return 0; return 1; */ } // int compare_for_qsort( const void *arg1, const void *arg2 ) void int_list_test(int nHowMany) { DWORD adwTimes[16] = {0}; // Times when we checked the system time // (in milliseconds, zero-terminated.) add_a_time(adwTimes); printf("RUNNING FUNCTION num_list_test(%d)\n", nHowMany); print_times(adwTimes); int *pnMyList = make_int_array(nHowMany); add_a_time(adwTimes); qsort((void *)pnMyList, nHowMany, sizeof(int), compare_for_qsort); add_a_time(adwTimes); print_ints(pnMyList, nHowMany); add_a_time(adwTimes); print_times(adwTimes); printf("EXITING FUNCTION num_list_test(%d)\n\n", nHowMany); free((void *) pnMyList); // Look, we can now explicitly see something // that we aren't timing in *any* of our versions! } // void int_list_test(int nHowMany) int main() { printf("hello world.\n"); int_list_test(20); //int_list_test(5000); int_list_test(50000); //int_list_test(100000); return 0; } // main()