Research portable Memory game | Исследовать портируемую игру Память
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

83 wiersze
2.1KB

  1. #include <stdlib.h> /* malloc */
  2. #include <sys/time.h> /* gettimeofday */
  3. #include <errno.h> /* perror */
  4. #include <stdio.h> /* printf */
  5. #include "uthash.h"
  6. #define BUFLEN 20
  7. #if 0
  8. #undef uthash_expand_fyi
  9. #define uthash_expand_fyi(tbl) printf("expanding to %d buckets\n", tbl->num_buckets)
  10. #endif
  11. typedef struct name_rec {
  12. char boy_name[BUFLEN];
  13. UT_hash_handle hh;
  14. } name_rec;
  15. int main(int argc,char *argv[])
  16. {
  17. name_rec *name, *names=NULL;
  18. char linebuf[BUFLEN];
  19. FILE *file;
  20. int i=0,j,nloops=3,loopnum=0,miss;
  21. struct timeval tv1,tv2;
  22. long elapsed_usec;
  23. if (argc > 1) {
  24. nloops = atoi(argv[1]);
  25. }
  26. if ( (file = fopen( "test14.dat", "r" )) == NULL ) {
  27. perror("can't open: ");
  28. exit(-1);
  29. }
  30. while (fgets(linebuf,BUFLEN,file) != NULL) {
  31. i++;
  32. if ( (name = (name_rec*)malloc(sizeof(name_rec))) == NULL) {
  33. exit(-1);
  34. }
  35. strcpy(name->boy_name, linebuf);
  36. HASH_ADD_STR(names,boy_name,name);
  37. }
  38. again:
  39. if (fseek(file,0,SEEK_SET) == -1) {
  40. fprintf(stderr,"fseek failed: %s\n", strerror(errno));
  41. }
  42. j=0;
  43. if (gettimeofday(&tv1,NULL) == -1) {
  44. perror("gettimeofday: ");
  45. }
  46. while (fgets(linebuf,BUFLEN,file) != NULL) {
  47. /* if we do 10 loops, the first has a 0% miss rate,
  48. * the second has a 10% miss rate, etc */
  49. miss = ((rand()*1.0/RAND_MAX) < (loopnum*1.0/nloops)) ? 1 : 0;
  50. /* generate a miss if we want one */
  51. if (miss) {
  52. linebuf[0]++;
  53. if (linebuf[1] != '\0') {
  54. linebuf[1]++;
  55. }
  56. }
  57. HASH_FIND_STR(names,linebuf,name);
  58. if (name) {
  59. j++;
  60. }
  61. }
  62. if (gettimeofday(&tv2,NULL) == -1) {
  63. perror("gettimeofday: ");
  64. }
  65. elapsed_usec = ((tv2.tv_sec - tv1.tv_sec) * 1000000) + (tv2.tv_usec - tv1.tv_usec);
  66. printf("lookup on %d of %d (%.2f%%) names succeeded (%.2f usec)\n", j, i,
  67. j*100.0/i, (double)(elapsed_usec));
  68. if (++loopnum < nloops) {
  69. goto again;
  70. }
  71. fclose(file);
  72. return 0;
  73. }