예제 #1
0
/*--------------------------------------------
 * color the remaining graph locally
 * return if finish or not
 * -----------------------------------------*/
void Node::colorLocally()
{
  // register leaf node
  CProxy_counter(counterGroup).ckLocalBranch()->registerMeLeaf();

#ifdef DEBUG
  char *id = new char[nodeID_.size()];
  strcpy(id, nodeID_.c_str());
  CkPrintf("Color locally in node [%s] with uncolored num=%d\n", id, uncolored_num_);
  delete [] id;
#endif

  if(0 == uncolored_num_) {
    mergeRemovedVerticesBack(deletedV, node_state_);

    if(is_root_) {
#ifdef DEBUG
      printGraph(true);
#endif
      CkPrintf("Vertex removal step at root removed all nodes\n");
      CkAssert(1 == isColoringValid(node_state_));

      CkExit();
    } else {
      parent_.finish(true, node_state_);
    }
    return;
  }

  bool wait = false;
  bool success = sequentialColoring(wait);

  // sequential coloring timed out. Return without sending any message to
  // parent. Sending of the response to the parent would be done in rerun()
  if(wait)
    return;

  if(success){
    mergeRemovedVerticesBack(deletedV, node_state_);

    if(is_root_){
      CkAssert(1 == isColoringValid(node_state_));
#ifdef DEBUG
      printGraph(true);
#endif

      CkExit();
    } else {
      parent_.finish(true, node_state_);
    }
  } else {
    if(is_root_){
      programEnd = CkTimer();
      printStats(node_state_, false);
      CkExit();
    } else {
      mergeRemovedVerticesBack(deletedV, node_state_);
      parent_.finish(false, node_state_);
    }
  }
}
예제 #2
0
파일: Main.C 프로젝트: pmatos/maxsatzilla
int main(int argc, char** argv)
{
    Solver      S;
    S.verbosity = 1;


    int         i, j;
    const char* value;
    for (i = j = 0; i < argc; i++){
        if ((value = hasPrefix(argv[i], "-polarity-mode="))){
            if (strcmp(value, "true") == 0)
                S.polarity_mode = Solver::polarity_true;
            else if (strcmp(value, "false") == 0)
                S.polarity_mode = Solver::polarity_false;
            else if (strcmp(value, "rnd") == 0)
                S.polarity_mode = Solver::polarity_rnd;
            else{
                reportf("ERROR! unknown polarity-mode %s\n", value);
                exit(0); }

        }else if ((value = hasPrefix(argv[i], "-rnd-freq="))){
            double rnd;
            if (sscanf(value, "%lf", &rnd) <= 0 || rnd < 0 || rnd > 1){
                reportf("ERROR! illegal rnd-freq constant %s\n", value);
                exit(0); }
            S.random_var_freq = rnd;

        }else if ((value = hasPrefix(argv[i], "-decay="))){
            double decay;
            if (sscanf(value, "%lf", &decay) <= 0 || decay <= 0 || decay > 1){
                reportf("ERROR! illegal decay constant %s\n", value);
                exit(0); }
            S.var_decay = 1 / decay;

        }else if ((value = hasPrefix(argv[i], "-verbosity="))){
            int verbosity = (int)strtol(value, NULL, 10);
            if (verbosity == 0 && errno == EINVAL){
                reportf("ERROR! illegal verbosity level %s\n", value);
                exit(0); }
            S.verbosity = verbosity;

        }else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--help") == 0){
            printUsage(argv);
            exit(0);

        }else if (strncmp(argv[i], "-", 1) == 0){
            reportf("ERROR! unknown flag %s\n", argv[i]);
            exit(0);

        }else
            argv[j++] = argv[i];
    }
    argc = j;


    reportf("This is MiniSat 2.0 beta\n");
#if defined(__linux__)
    fpu_control_t oldcw, newcw;
    _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw);
    reportf("WARNING: for repeatability, setting FPU to use double precision\n");
#endif
    double cpu_time = cpuTime();

    solver = &S;
    signal(SIGINT,SIGINT_handler);
    signal(SIGHUP,SIGINT_handler);

    if (argc == 1)
        reportf("Reading from standard input... Use '-h' or '--help' for help.\n");

    gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb");
    if (in == NULL)
        reportf("ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1);

    reportf("============================[ Problem Statistics ]=============================\n");
    reportf("|                                                                             |\n");

    parse_DIMACS(in, S);
    gzclose(in);
    FILE* res = (argc >= 3) ? fopen(argv[2], "wb") : NULL;

    double parse_time = cpuTime() - cpu_time;
    reportf("|  Parsing time:         %-12.2f s                                       |\n", parse_time);

    if (!S.simplify()){
        reportf("Solved by unit propagation\n");
        if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res);
        printf("UNSATISFIABLE\n");
        exit(20);
    }

    bool ret = S.solve();
    printStats(S);
    reportf("\n");
    printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n");
    if (res != NULL){
        if (ret){
            fprintf(res, "SAT\n");
	    //S.liftModel();
            for (int i = 0; i < S.nVars(); i++)
                if (S.model[i] != l_Undef)
                    fprintf(res, "%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1);
	    //else fprintf(res, "\nuninstanciated variable %d\n", i+1);
            fprintf(res, " 0\n");
        }else
            fprintf(res, "UNSAT\n");
        fclose(res);
    }

#ifdef NDEBUG
    exit(ret ? 10 : 20);     // (faster than "return", which will invoke the destructor for 'Solver')
#endif
}
예제 #3
0
파일: main.c 프로젝트: kennethisom/f4.9
int main(int argc, char **argv) {

    printf("F 4.9  Copyright (C) 2013\n");
    printf("This is free software, and you are welcome to redistribute it\n");
    printf("You should have received a copy of the GNU General Public License\n");
    printf("along with this program. GPL version 3 or later,\nIf not, see <http://www.gnu.org/licenses/>.\n\n");
    
    if(argc < 2) {
        usage(argv[0]);
    }

    char c;
    char* cover = NULL;
    char* inFile = NULL;
    char* outFile = NULL;
    char* outputJPEGName = NULL;

    int meK = 3;
    int prngKey = 31;
    int quality = 100;
    int ret = EXIT_FAILURE;

    enum {
        encode, decode, stats
    } operation;

    while ((c = getopt (argc, argv, "edsi:q:k:p:i:s:c:o:")) != -1) {

        switch (c) {
            case 'c':
                cover = optarg;
                break;
            case 'd':
                operation = decode;
                break;
            case 'e':
                operation = encode;
                break;
            case 'i':
                inFile = optarg;
                break;
            case 'k':
                meK = atoi(optarg);
                break;
            case 'o':
                outFile = optarg;
                break;
            case 'p':
                prngKey = atoi(optarg);
                break;
            case 'q':
                quality = atoi(optarg);
                break;
            case 's':
                operation = stats;
                break;
            case '?':

                if (isprint (optopt)) {
                    fprintf(stderr, "Unknown option `-%c'.\n", optopt);
                    usage(argv[0]);
                }else{
                    fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
                    usage(argv[0]);
                }
            default:
                usage(argv[0]);
        }
    }
 
    switch(operation) {
        case decode:

            fprintf(stderr, "\nDecoding\n");

            if(EXIT_FAILURE == stegoF5(outFile, inFile, NULL, (stegoOperation) decodeData, prngKey, quality, meK)) {
                printf("\nSomething went wrong, please check your usage and try again!\n");
            } else {
                ret = EXIT_SUCCESS;
            }
            break;

        case encode:

            fprintf(stderr, "\nEncoding\n");

            if(outFile != NULL) {
                fprintf(stderr, "\nYou can't use the output flag when encoding!\n");
                exit(EXIT_FAILURE);
            }

            if(cover != NULL && inFile != NULL && outFile == NULL) {
                int len = strlen(cover);
                int maxLen = len + 500;//support for directories with long names
                outputJPEGName = calloc(maxLen, 1);
                strncat(outputJPEGName, cover, len);
                snprintf(outputJPEGName+len, maxLen, "_%i_q_%i_key_%i_k.jpeg", quality, prngKey,  meK);
                printf("\nValues:\n\tHide: %s inside of: %s with %i quality and %i as the key with %i as the K-N schema\n", inFile, cover, quality, prngKey, meK);
                printf("\nSaving files as: %s\n", outputJPEGName);
            }

            if(EXIT_FAILURE == stegoF5(inFile, cover, outputJPEGName, (stegoOperation) encodeData, prngKey, quality, meK)) {
                printf("\nSomething went wrong, please check your usage and try again!\n");
            } else {
                ret = EXIT_SUCCESS;
            }

            free(outputJPEGName);
            break;

        case stats:

            printStats(inFile, cover, outFile, prngKey);
            break;

        default:
            break;
    }

    return ret;
}
예제 #4
0
파일: whosh.cpp 프로젝트: osm-spline/whosh
 void callback_after_nodes() {
     printStats();
     finishHim(node_conn);
 }
예제 #5
0
int asc_support_main(ATerm *bottomOfStack, int argc, char *argv[], void (*register_all)(), void (*resolve_all)(), void (*init_all)(), unsigned const char* tableBaf, size_t tableSize, ATbool parseInput, ATBhandler handler) {

  PT_ParseTree pt = NULL;
  PT_Tree asfix;
  PT_Tree trm;
  PT_ParseTree rpt = NULL;
  ATerm reduct;
  const char *outputFilename;
  int numberOfInputs;

  ATinit(argc, argv, bottomOfStack);
  initApis();

  register_all();
  resolve_all();
  init_all();

  initParsetable(tableBaf, tableSize);
  SGLR_initialize();

  OPT_initialize();
  ASC_initializeDefaultOptions();

  /*  Check whether we're a ToolBus process  */
  if (toolbusMode(argc, argv)) {
    ATBinit(argc, argv, bottomOfStack);
    ATBconnect(NULL, NULL, -1, asf_toolbus_handler);
    ATBeventloop();
  }
  else {    
    handleOptions(argc, argv, parseInput);

    numberOfInputs = ASC_getNumberOfParseTrees();
    outputFilename = ASC_getOutputFilename();

    if (!streq(ASC_getPrefixFunction(),"")) {
      pt = applyFunction((const char*) ASC_getPrefixFunction(), 
			 (const char*) ASC_getResultNonTermName(), numberOfInputs, inputs);
    } 
    else {
      if (numberOfInputs == 0) {
	pt = parsetreeFromFile("-", parseInput);
      }
      else if (numberOfInputs == 1) {
	pt = inputs[0];
      }
      else if (numberOfInputs != 1) {
	ATerror("Can only process one argument if no -f and -r option "
		"are supplied.\n"
		"Did a -s argument eat up your -f or -r option?\n");
	return 1;
      }
    }

    if (PT_isValidParseTree(pt)) {
      trm = PT_getParseTreeTop(pt);

      if (ASC_getVerboseFlag()) { ATfprintf(stderr,"Reducing ...\n"); }

      reduct = innermost(trm);

      if (ASC_getVerboseFlag()) { ATfprintf(stderr,"Reducing finished.\n"); }
      if (ASC_getStatsFlag())  { printStats(); }

      if (ASC_getOutputFlag()) {
	asfix = toasfix(reduct);
	rpt = PT_makeParseTreeTop(asfix, 0);

	if (parseInput) {
	  FILE *fp = NULL;

	  if (!strcmp(outputFilename, "-")) {
	    fp = stdout;
	  }
	  else {
	    fp = fopen(outputFilename, "wb");
	  }

	  if (fp != NULL) {
	    PT_yieldParseTreeToFile(rpt, fp, ATfalse);
	  }
	  else {
	    ATerror("asc-main: unable to open %s for writing\n", outputFilename);
	  }
	}
	else {
	  if (ASC_getBafmodeFlag()) {
	    ATwriteToNamedBinaryFile(PT_ParseTreeToTerm(rpt),outputFilename);
	  }
	  else {
	    ATwriteToNamedTextFile(PT_ParseTreeToTerm(rpt),outputFilename);
	  }
	}
      }
    }
  }

  return 0;
}
예제 #6
0
void Collector::postCollect() {
	printStats();
	gcsSinceLastPromotionPhase++;
}
예제 #7
0
int main( int argc, char* argv[ ] ) {
	Playlist *myList = NULL;
	int minutes, seconds;
	char *name, *title, *artist;
	Option opt;

	printf("\n\nWelcome to project 5 - music playlists\n\n");
	opt = getAction();
	while (opt != QUIT) {
		switch (opt) {
			case ADD_LIST:
				printf("Adding a new playlist to start of library\n");
				name = getString("Enter the name of the new playlist");
				printf("\nAdding the playlist '%s' to your library (at front of library) \n", name);
				myList = add(myList, name);
				break;
			case ADD_SONG:
				printf("Add a song to an existing playlist\n");
				name = getString("Enter the name of the playlist");
				title = getString("Enter the title of the song to add");
				artist = getString("Enter the name of the artist");
				getTime(&minutes, &seconds);
				printf("\nAdding the song below to the playlist '%s' (at end of playlist)\n", name);
				printf("\tTitle : %s\n", title);
				printf("\tArtist: %s\n", artist);
				printf("\tLength: %d:%d\n", minutes, seconds);
				addSong(myList, name, title, artist, minutes, seconds);
				break;
			case PRINT_LIST:
				printf("Print the songs in a playlist\n");
				name = getString("Enter the name of the playlist");
				printf("\nPrinting the names of all songs in the playlist '%s'\n", name);
				printSongs(myList, name);
				break;
			case LIST_SIZE:
				printf("Print the size of a playlist\n");
				name = getString("Enter the name of the playlist");
				printf("\nThe playlist '%s' contains N songs and has NN:NN minutes of music\n", name);
				printSize(myList, name);
				break;
			case STATS:
				printf("Print statistics on all your playslists\n");
				printStats(myList);
				break;
			case ADD_LIST_ORDERED:
				printf("Adding a new playlist to library (ordered)\n");
				name = getString("Enter the name of the new playlist");
				printf("\nAdding the playlist '%s' to your library (in alphabetical order)\n", name);
				myList = addOrdered(myList, name);
				break;
			case ADD_SONG_ORDERED:
				printf("Add a song to an existing playlist (ordered)\n");
				name = getString("Enter the name of the playlist");
				title = getString("Enter the title of the song to add");
				artist = getString("Enter the name of the artist");
				getTime(&minutes, &seconds);
				printf("\nAdding the song below to the playlist '%s' (in alphabetical order)\n", name);
				printf("\tTitle : %s\n", title);
				printf("\tArtist: %s\n", artist);
				printf("\tLength: %d:%d\n", minutes, seconds);
				addSongOrdered(myList, name, title, artist, minutes, seconds);
				break;
			case REMOVE_SONG:
				printf("Removing a song from an existing playlist\n");
				name = getString("Enter the name of the playlist");
				title = getString("Enter the title of the song to remove");
				artist = getString("Enter the artist of the song to remove");
				printf("\nRemoving the song '%s' by '%s' from the playlist %s\n", title, artist, name);
				removeSong(myList, name, title, artist);
				break;
			case REMOVE_LIST:
				printf("Removing a playlist\n");
				name = getString("Enter the name of the playlist to remove");
				printf("\nRemoving the the playlist %s from your library\n", name);
				myList = removeList(myList, name);
				break;
			case HELP:
				optionDetails();
				break;
			default: break;
		}
		opt = getAction();
	}
	return 0;
}
예제 #8
0
void CAMDataDePrivate::print(ostream& out) const
{
    printStats(out);
}
예제 #9
0
int
main (int argc, char *argv[])
{
  double t, tv[2];

  int reps = 10000;
  int doprint = 0;
  char *progName;
  int minWords = 1;
  int maxWords = 1;
  int incWords;
  int nwords;
  int nproc;
  int proc;
  int peer;
  int c;
  int r;
  int i;
  long *rbuf;
  long *tbuf;

  start_pes (0);

  proc = _my_pe ();
  nproc = _num_pes ();

  for (progName = argv[0] + strlen (argv[0]);
       progName > argv[0] && *(progName - 1) != '/'; progName--)
    ;

  while ((c = getopt (argc, argv, "n:eh")) != -1)
    switch (c)
      {
      case 'n':
	if ((reps = getSize (optarg)) <= 0)
	  usage (progName);
	break;

      case 'e':
	doprint++;
	break;

      case 'h':
	help (progName);

      default:
	usage (progName);
      }

  if (optind == argc)
    minWords = 1;
  else if ((minWords = getSize (argv[optind++])) <= 0)
    usage (progName);

  if (optind == argc)
    maxWords = minWords;
  else if ((maxWords = getSize (argv[optind++])) < minWords)
    usage (progName);

  if (optind == argc)
    incWords = 0;
  else if ((incWords = getSize (argv[optind++])) < 0)
    usage (progName);

  if (!(rbuf = (long *) shmalloc (maxWords * sizeof (long))))
    {
      perror ("Failed memory allocation");
      exit (1);
    }
  memset (rbuf, 0, maxWords * sizeof (long));
  shmem_barrier_all ();

  if (!(tbuf = (long *) malloc (maxWords * sizeof (long))))
    {
      perror ("Failed memory allocation");
      exit (1);
    }

  if (nproc == 1)
    return 0;

  for (i = 0; i < maxWords; i++)
    tbuf[i] = 1000 + (i & 255);

  if (doprint)
    printf
      ("%d(%d): Shmem PING reps %d minWords %d maxWords %d incWords %d\n",
       proc, nproc, reps, minWords, maxWords, incWords);

  shmem_barrier_all ();

  peer = proc ^ 1;
  if (peer >= nproc)
    doprint = 0;

  for (nwords = minWords;
       nwords <= maxWords;
       nwords = incWords ? nwords + incWords : nwords ? 2 * nwords : 1)
    {
      r = reps;

      shmem_barrier_all ();

      tv[0] = gettime ();

      if (peer < nproc)
	{
	  if (proc & 1)
	    {
	      r--;
	      shmem_wait (&rbuf[nwords - 1], 0);
	      rbuf[nwords - 1] = 0;
	    }

	  while (r-- > 0)
	    {
	      shmem_long_put (rbuf, tbuf, nwords, peer);
	      shmem_wait (&rbuf[nwords - 1], 0);
	      rbuf[nwords - 1] = 0;
	    }

	  if (proc & 1)
	    shmem_long_put (rbuf, tbuf, nwords, peer);
	}

      tv[1] = gettime ();


      t = dt (&tv[1], &tv[0]) / (2 * reps);

      shmem_barrier_all ();

      printStats (proc, peer, doprint, nwords, t);
    }

  shmem_barrier_all ();

  free (tbuf);
  shfree (rbuf);

  return 0;
}
예제 #10
0
파일: master.c 프로젝트: geoffchu/chuffed
void Master::solve() {  

        lastCubeFinished = wallClockTime();
        num_threads = so.num_threads;
        job_start_time.growTo(num_threads, DONT_DISTURB);
        job_start_time_backup.growTo(num_threads, DONT_DISTURB);
        cur_job.growTo(num_threads, NULL);
        lhead.growTo(num_threads, 0);
        last_send_learnts.growTo(num_threads, 0);
        global_learnts.reserve(10000000);
        long maxCycleTime = 0;
        stoppedInit = false;
        if(engine.opt_var){
          bestObjReceived = engine.opt_type ? engine.opt_var->getMin() : engine.opt_var->getMax();
        }
        
        if(so.purePortfolio){
          for(int i = 0 ; i < num_threads ; i++)
            job_queue.push(new SClause());
        }
        else
          job_queue.push(new SClause());
        
        for(int i = 0 ; i < num_threads ; i++){
          if(so.greedyInit && (i  % 3 < 2)){
            slaveStates.push_back(RUNNING_GREEDY);
            slavesRunningGreedy++;
            setState(i, RUNNING_GREEDY);
          }
          else{
            slaveStates.push_back(NORMAL_SEARCH);
            setState(i, NORMAL_SEARCH);
          }
        } 

        MPI_Buffer_attach(malloc(MPI_BUFFER_SIZE), MPI_BUFFER_SIZE);

        // Search:
        int lastPrinted = time(NULL);
        int tStart = lastPrinted;
        long lastSleep = clock();
        bool stealJobsNow = true;
        while (status == RES_UNK && time(NULL) < so.time_out) {
                //fprintf(stderr, "Trying to send jobs...\n");
                while (num_free_slaves > 0 && job_queue.size() > 0) {
                  if(!sendJob())
                    break;
                }
                /**************************************************************************
                 * Ask all jobs to finish the first phase, if this has not happened yet.
                 * */
                if(!stoppedInit &&  time(NULL) > engine.half_time){
                  if(PAR_DEBUG) fprintf(stderr, "Asking remaining init-workers to continue with normal search...\n");
                  for(int i = 0 ; i < num_threads ; i++){
                    if(slaveStates[i] == RUNNING_GREEDY){
                      setState(i, NORMAL_SEARCH);
                    }
                  }
                  stoppedInit = true;
                }
                int received;
                MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &received, &s);
                if (received) {
                        double t;
                        profile_start();
                      //  printf("Profiling started...\n");
                        switch (s.MPI_TAG) {
                                case REPORT_TAG:
                                    //    printf("It was a report!\n");
                                        receiveReport();
                                    //    printf("ReceiveReport done!\n");
                                        profile_end("receive report", 0);
                                        continue;
                                case SPLIT_TAG:
                                     //   printf("Split tag received!\n");
                                        receiveJobs();
                                        profile_end("receive jobs", 0);
                                        continue;
                                case REPORT_SOLUTION_TAG:
                                    if(PAR_DEBUG) fprintf(stderr, "Received solution! \n");
                                    receiveSolution();
                                    continue;
                                case REPORT_OPTIMUM_TAG:
                                  receiveOptObj();
                                  continue;
                                case SOLUTION_PHASE_TAG:
                                  receivePhase();
                                  continue;
                                case SLAVE_NEW_STATE_TAG:
                                  int dummy;
                                  MPI_Recv(&dummy, 1, MPI_INT, s.MPI_SOURCE, SLAVE_NEW_STATE_TAG, MPI_COMM_WORLD, &s);
                                  if(PAR_DEBUG) fprintf(stderr, "Setting state of slave %d to %d\n", s.MPI_SOURCE-1, dummy);
                                  if(slaveStates[s.MPI_SOURCE-1] == RUNNING_GREEDY && dummy == NORMAL_SEARCH)
                                    slavesRunningGreedy--;
                                  slaveStates[s.MPI_SOURCE-1] = dummy;
                                  continue;
                                  continue;
                                default:
                                        assert(false);
                        }
                }
                if (job_queue.size() < 2*num_threads-2 && !so.purePortfolio ) { 
                  // Steal jobs if 
                  // - normal mode
                  // - greedy-init, and at least one job finished now...
                  if(!so.greedyInit || slavesRunningGreedy < num_threads){
                    stealJobs(); 
                    //continue; 
                  }
                  
                }
                
                long now = clock();
                maxCycleTime = std::max(maxCycleTime, now - lastSleep);
                usleep(500);
                lastSleep = clock();
                
                
        }
        if (PAR_DEBUG){
          fprintf(stderr, "Waiting for slaves to terminate...\n");
          fprintf(stderr, "Max cycle time: %d (%lf)\n", maxCycleTime, (double)maxCycleTime/CLOCKS_PER_SEC);
          fprintf(stderr, "End of problem called\n");
        }
        MPI_Request r;
        for (int i = 0; i < num_threads; i++) {
                MPI_Isend(NULL, 0, MPI_INT, i+1, INTERRUPT_TAG, MPI_COMM_WORLD, &r);
                MPI_Isend(NULL, 0, MPI_INT, i+1, FINISH_TAG, MPI_COMM_WORLD, &r);
        }

        while (num_free_slaves != num_threads) {
                MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &s);
                int thread_no = s.MPI_SOURCE-1;

                MPI_Get_count(&s, MPI_INT, &message_length);
                message = (int*) malloc(message_length*sizeof(int));
                MPI_Recv(message, message_length, MPI_INT, s.MPI_SOURCE, s.MPI_TAG, MPI_COMM_WORLD, &s);
                if (s.MPI_TAG == REPORT_TAG) {
                        if (message[0] != RES_SEA) {
                                assert(job_start_time[thread_no] != NOT_WORKING);
                                num_free_slaves++;
                                job_start_time[thread_no] = NOT_WORKING;
                                if (PAR_DEBUG) fprintf(stderr, "%d is free, %f\n", thread_no, wallClockTime());
                        }
                }

                free(message);
        }

        collectStats();
        if(PAR_DEBUG) fprintf(stderr, "Master terminating with obj in %d and %d, bestResult= %d\n", engine.opt_var->getMin(), engine.opt_var->getMax(), bestObjReceived);
        if(so.verbosity > 0)
          printStats();

}
예제 #11
0
static int clangTidyMain(int argc, const char **argv) {
  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
                                    cl::ZeroOrMore);

  auto OptionsProvider = createOptionsProvider();
  if (!OptionsProvider)
    return 1;

  StringRef FileName("dummy");
  auto PathList = OptionsParser.getSourcePathList();
  if (!PathList.empty()) {
    FileName = PathList.front();
  }
  ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
  std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);

  if (ListChecks) {
    llvm::outs() << "Enabled checks:";
    for (auto CheckName : EnabledChecks)
      llvm::outs() << "\n    " << CheckName;
    llvm::outs() << "\n\n";
    return 0;
  }

  if (DumpConfig) {
    EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
    llvm::outs() << configurationAsText(
                        ClangTidyOptions::getDefaults().mergeWith(
                            EffectiveOptions))
                 << "\n";
    return 0;
  }

  if (EnabledChecks.empty()) {
    llvm::errs() << "Error: no checks enabled.\n";
    llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
    return 1;
  }

  if (PathList.empty()) {
    llvm::errs() << "Error: no input files specified.\n";
    llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
    return 1;
  }

  ProfileData Profile;

  std::vector<ClangTidyError> Errors;
  ClangTidyStats Stats =
      runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
                   PathList, &Errors,
                   EnableCheckProfile ? &Profile : nullptr);
  bool FoundErrors =
      std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
        return E.DiagLevel == ClangTidyError::Error;
      }) != Errors.end();

  const bool DisableFixes = Fix && FoundErrors && !FixErrors;

  // -fix-errors implies -fix.
  handleErrors(Errors, (FixErrors || Fix) && !DisableFixes);

  if (!ExportFixes.empty() && !Errors.empty()) {
    std::error_code EC;
    llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
    if (EC) {
      llvm::errs() << "Error opening output file: " << EC.message() << '\n';
      return 1;
    }
    exportReplacements(Errors, OS);
  }

  printStats(Stats);
  if (DisableFixes)
    llvm::errs()
        << "Found compiler errors, but -fix-errors was not specified.\n"
           "Fixes have NOT been applied.\n\n";

  if (EnableCheckProfile)
    printProfileData(Profile, llvm::errs());

  return 0;
}
예제 #12
0
int main(int argc, char** argv)
{
    Solver      S;
    bool        st;

    if (argc >= 2 && strlen(argv[1]) >= 5 && strcmp(&argv[1][strlen(argv[1])-5], ".bcnf") == 0)
        st = parse_BCNF(argv[1], S);
    else{
        parse_DIMACS(argv[1], S);
        st = S.okay();
        /*
        gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb");
        if (in == NULL)
            fprintf(stderr, "ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]),
            exit(1);
        st = parse_DIMACS(in, S);
        gzclose(in);
        */
    }
    FILE* res = (argc >= 3) ? fopen(argv[2], "wb") : NULL;

    if (!st){
        if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res);
        reportf("Trivial problem\n");
        reportf("UNSATISFIABLE\n");
      #ifdef SAT_LIVE
        printf("s UNSATISFIABLE\n");
      #endif
        exit(20);
    }

    S.verbosity = 1;
    solver = &S;
    signal(SIGINT,SIGINT_handler);
    signal(SIGHUP,SIGINT_handler);
    st = S.solve();
    printStats(S.stats, cpuTime());
    reportf("\n");
    reportf(st ? "SATISFIABLE\n" : "UNSATISFIABLE\n");

    if (res != NULL){
        if (st){
            fprintf(res, "SAT\n");
            for (int i = 0; i < S.nVars(); i++)
                if (S.model[i] != l_Undef)
                    fprintf(res, "%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1);
            fprintf(res, " 0\n");
        }else
            fprintf(res, "UNSAT\n");
        fclose(res);
    }

  #ifdef SAT_LIVE
    printf(st ? "s SATISFIABLE\n" : "s UNSATISFIABLE\n");
    if (st){
        printf("v");
        for (int i = 0; i < S.nVars(); i++)
            if (S.model[i] != l_Undef)
                printf(" %s%d", (S.model[i]==l_True)?"":"-", i+1);
        printf(" 0\n");
    }
  #endif

    exit(st ? 10 : 20);     // (faster than "return", which will invoke the destructor for 'Solver')
}
예제 #13
0
static void SIGINT_handler(int signum) {
    printStats(solver->stats, cpuTime());
    reportf("\n");
    reportf("INTERRUPTED\n");
    exit(0); }
예제 #14
0
int
main (int argc, char* argv[])
{
  int option_char;
  int NTRIALS = 1;
  int N = 1000000;
  char *filename = NULL;

  while ((option_char = getopt(argc, argv, "t:n:o:h")) != -1) {
    switch (option_char) {
      case 't': 
        NTRIALS = atoi(optarg);
        break;
      case 'n':
        N = atoi(optarg);
        break;
      case 'o':
        filename = optarg;
        break;
      case 'h':
        fprintf(stderr, "%s\n", USAGE);
        exit(EXIT_SUCCESS);
        break;                      
      default:
        fprintf(stderr, "%s\n", USAGE);
        exit(EXIT_FAILURE);
    }
  }

  long double* T = (long double*) malloc(NTRIALS * sizeof(long double));

  long *next = (long*) malloc(N * sizeof(long));
  long *par_rank = (long*) malloc(N * sizeof(long));
  long *seq_rank = (long*) malloc(N * sizeof(long));
  size_t ncorrect = 0;

  for(int i = 0; i < NTRIALS; i++){

    initRandomList(next, N);

    long head = seqFindHead(next, N);

    seqListRanks(head, next, seq_rank, N);

    stopwatch_t watch = stopwatch_start();
    parallelListRanks(head, next, par_rank, N);
    T[i] = stopwatch_stop(watch);

    if( memcmp(seq_rank, par_rank, N * sizeof(long)) == 0)
      ncorrect++;
  }

  if (!filename)
    printStats(stdout, T, ncorrect, NTRIALS, N);
  else{
    FILE *fp;
    fp = fopen(filename, "w");
    printStats(fp, T, ncorrect, NTRIALS, N);
    fclose(fp);
  }

  free(next);
  free(par_rank);
  free(seq_rank);
  free(T);

  return EXIT_SUCCESS;
}
예제 #15
0
파일: sping.c 프로젝트: coti/oshmpi
int main (int argc, char *argv[])
{
	double t,tv[2];
	int reps = DFLT_REPS;
	int doprint = 1/*0*/;
	char *progName;
	int minWords;
	int maxWords;
	int incWords, nwords, nproc, proc, peer, c, r, i;
	long *rbuf;	/* remote buffer - sink */
	long *tbuf;	/* transmit buffer - src */

	start_pes(0);
	proc = _my_pe();
	nproc = _num_pes();
	if (nproc == 1) {
		fprintf(stderr, "ERR - Requires > 1 Processing Elements\n");
		return 1;
	}

	for (progName = argv[0] + strlen(argv[0]);
		 progName > argv[0] && *(progName - 1) != '/';
		 progName--)
		;

	while ((c = getopt (argc, argv, "n:evh")) != -1)
		switch (c)
		{
		case 'n':
			if ((reps = getSize (optarg)) <= 0)
				usage (progName);
			break;
		case 'e':
			doprint++;
			break;
		case 'v':
			Verbose++;
			break;
		case 'h':
			help (progName);
		default:
			usage (progName);
		}

	if (optind == argc)
		minWords = DFLT_MIN_WORDS;
	else if ((minWords = getSize (argv[optind++])) <= 0)
		usage (progName);

	if (optind == argc)
		maxWords = minWords;
	else if ((maxWords = getSize (argv[optind++])) < minWords)
		usage (progName);

	if (optind == argc)
		incWords = 0;
	else if ((incWords = getSize (argv[optind++])) < 0)
		usage (progName);

	if (!(rbuf = (long *)shmalloc(maxWords * sizeof(long))))
	{
		perror ("Failed memory allocation");
		exit (1);
	}
	memset (rbuf, 0, maxWords * sizeof (long));

	if (!(tbuf = (long *)shmalloc(maxWords * sizeof(long))))
	{
		perror ("Failed memory allocation");
		exit (1);
	}

	for (i = 0; i < maxWords; i++)
		tbuf[i] = 1000 + (i & 255);

	if (doprint)
		printf ("%d(%d): Shmem PING reps %d minWords %d maxWords %d "
				"incWords %d\n",
				proc, nproc, reps, minWords, maxWords, incWords);

        dprint("[%d] rbuf: %ld\n", proc, (unsigned long) rbuf);

	shmem_barrier_all();

	peer = proc ^ 1;
	if (peer >= nproc)
		doprint = 0;

	for (nwords = minWords;
		 nwords <= maxWords;
		 nwords = incWords ? nwords + incWords : nwords ? 2 * nwords : 1)
	{
		r = reps;
		shmem_barrier_all();
		tv[0] = gettime();
		if (peer < nproc)
		{
			if (proc & 1)
			{
				r--;
				shmem_wait(&rbuf[nwords-1], 0);
				rbuf[nwords-1] = 0;
			}

			while (r-- > 0)
			{
				shmem_long_put(rbuf, tbuf, nwords, peer);
				shmem_wait(&rbuf[nwords-1], 0);
				rbuf[nwords-1] = 0;
			}

			if (proc & 1)
			{
				shmem_long_put(rbuf, tbuf, nwords, peer);
			}
		}
		tv[1] = gettime();
		t = dt (&tv[1], &tv[0]) / (2 * reps);

		shmem_barrier_all();

		printStats (proc, peer, doprint, nwords, t);
	}

    shfree(rbuf);
    shfree(tbuf);

	shmem_barrier_all();
	return 0;
}
예제 #16
0
파일: queuegroup.c 프로젝트: 26597925/cnats
int main(int argc, char **argv)
{
    natsConnection      *conn = NULL;
    natsOptions         *opts  = NULL;
    natsSubscription    *sub   = NULL;
    natsStatistics      *stats = NULL;
    natsMsg             *msg   = NULL;
    natsStatus          s;

    opts = parseArgs(argc, argv, usage);

    printf("Listening %ssynchronously on '%s' with name '%s'.\n",
           (async ? "a" : ""), subj, name);

    s = natsOptions_SetErrorHandler(opts, asyncCb, NULL);

    if (s == NATS_OK)
        s = natsConnection_Connect(&conn, opts);

    if (s == NATS_OK)
    {
        if (async)
            s = natsConnection_QueueSubscribe(&sub, conn, subj, name, onMsg, NULL);
        else
            s = natsConnection_QueueSubscribeSync(&sub, conn, subj, name);
    }

    // For maximum performance, set no limit on the number of pending messages.
    if (s == NATS_OK)
        s = natsSubscription_SetPendingLimits(sub, -1, -1);

    if (s == NATS_OK)
        s = natsSubscription_AutoUnsubscribe(sub, (int) total);

    if (s == NATS_OK)
        s = natsStatistics_Create(&stats);

    if ((s == NATS_OK) && async)
    {
        while (s == NATS_OK)
        {
            s = printStats(STATS_IN|STATS_COUNT,conn, sub, stats);

            if (count == total)
                break;

            if (s == NATS_OK)
                nats_Sleep(1000);
        }
    }
    else if (s == NATS_OK)
    {
        int64_t last = 0;

        for (count = 0; (s == NATS_OK) && (count < total); count++)
        {
            s = natsSubscription_NextMsg(&msg, sub, 10000);
            if (s != NATS_OK)
                break;

            if (start == 0)
                start = nats_Now();

            if (nats_Now() - last >= 1000)
            {
                s = printStats(STATS_IN|STATS_COUNT,conn, sub, stats);
                last = nats_Now();
            }

            natsMsg_Destroy(msg);
        }
    }

    if (s == NATS_OK)
    {
        printPerf("Received", total, start, elapsed);
    }
    else
    {
        printf("Error: %d - %s\n", s, natsStatus_GetText(s));
        nats_PrintLastErrorStack(stderr);
    }

    // Destroy all our objects to avoid report of memory leak
    natsStatistics_Destroy(stats);
    natsSubscription_Destroy(sub);
    natsConnection_Destroy(conn);
    natsOptions_Destroy(opts);

    // To silence reports of memory still in used with valgrind
    nats_Close();

    return 0;
}
예제 #17
0
void process_data(FILE *input_file) {
    // !! your code should start here.  the input_file parameter
    // is an already-open file.  you can read data from it using
    // the fgets() C library function.  close it with the fclose()
    // built-in function

	//CPU time starting stuff
	struct rusage userUsage, systemUsage;
	struct timeval userStart, userEnd, systemStart, systemEnd;
	getrusage(RUSAGE_SELF, &userUsage);
	getrusage(RUSAGE_SELF, &systemUsage);
	userStart = userUsage.ru_utime;
	systemStart = systemUsage.ru_stime;

/* //this is from when we tried to be fancy
	//input from stdin
	if(input_file == stdin) {
		char buffer[240];
		char finalstr[666];
		while(1) {
			printf("Enter a value (Ctrl+D to exit): ");
			if(fgets(buffer,240,stdin) == NULL) {
				break;
			}
			strcat(finalstr,buffer);
			printf("%s\n",finalstr);
		}
		printf("\n");
	}
*/
	//iterate through the file + make a counter to count up the total size of the file
	char str[sizeof(*input_file)] = "";
	int maxSize = 0;
	while(fgets(str,sizeof(*input_file),input_file) != NULL) {
		maxSize += sizeof(*input_file); //counting up total size of the file
	}
	
	char finalstr[maxSize]; //initialize a single string for the whole file
	
	//iterate through the file again, this time putting the whole thing as a single string for tokenify to work with
	rewind(input_file); //resets fgets
	while(fgets(str,sizeof(*input_file),input_file) != NULL) {
		strcat(finalstr,str);
	}
	deleteComments(finalstr);
	char** tokens = tokenify(finalstr);
	//printf("%s",finalstr);
	refineToken(tokens);
	//print_tokens(tokens);

	//linked list creation
	struct node *head = NULL;
	int i = 0;
    while (tokens[i] != NULL) {
		list_append(tokens[i],&head);
        i++;
    }
	free_tokens(tokens); //appears to work (checked using valgrind ... --leak-check=full)
	//list_print(head);
	list_sort(&head);
	
	//CPU time ending stuff
	getrusage(RUSAGE_SELF, &userUsage);
	getrusage(RUSAGE_SELF, &systemUsage);
	systemEnd = systemUsage.ru_stime;
	userEnd = userUsage.ru_utime;
	
	float userTime = (userEnd.tv_sec + userEnd.tv_usec) - (userStart.tv_sec + userStart.tv_usec);
	float systemTime = (systemEnd.tv_sec + systemEnd.tv_usec) - (systemStart.tv_sec + systemStart.tv_usec);
	printStats(head,userTime,systemTime);
	
	list_clear(head);
}
예제 #18
0
파일: cntGlue.c 프로젝트: davidhoover/kent
int main(int argc, char *argv[])
{
struct hash *bacHash;
char line[1024];
int lineCount;
char *words[256];
int wordCount;
int fileIx;
char *fileName;
FILE *f;

if (argc < 2)
    usage();
bacHash = newHash(16);

for (fileIx = 1; fileIx < argc; ++fileIx)
    {
    fileName = argv[fileIx];
    uglyf("Processing %s\n", fileName);
    f = mustOpen(fileName, "r");
    lineCount = 0;
    while (fgets(line, sizeof(line), f))
        {
        ++lineCount;
        wordCount = chopLine(line, words);
        if (wordCount == ArraySize(words))
            errAbort("Too many words line %d of %s\n", lineCount, fileName);
        if (wordCount != 0)
            {
            char *bacName;
            int cIx;
            struct contigTrack *ctList = NULL, *ct;
            struct bacTrack *bt;
            struct hashEl *hel;

            /* Check line syntax and parse it. */
            if (!sameString(words[1], "glues"))
                errAbort("Bad format line %d of %s\n", lineCount, fileName);
            bacName = words[2];
            for (cIx = 4; cIx < wordCount; cIx += 5)
                {
                char *parts[3];
                int partCount;

                AllocVar(ct);
                ct->ix = atoi(words[cIx]);
                ct->strand = words[cIx+1][0];
                ct->dir = words[cIx+2][0];
                partCount = chopString(words[cIx+3], "(-)", parts, ArraySize(parts));
                if (partCount != 2)
                    errAbort("Bad format line %d of %s\n", lineCount, fileName);
                ct->start = atoi(parts[0]);
                ct->end = atoi(parts[1]);
                ct->cookedScore = atof(words[cIx+4]);
                slAddHead(&ctList, ct);                
                }
            slSort(&ctList, cmpContigTrack);
        
            /* Lookup bacTrack and make it if new. */
            hel = hashLookup(bacHash, bacName);
            if (hel == NULL)
                {
                AllocVar(bt);
                hel = hashAdd(bacHash, bacName, bt);
                bt->name = hel->name;
                slAddHead(&bacList, bt);
                }
            else
                {
                bt = hel->val;
                }
            
            /* Process pairs into bacTrack. */
            addPairs(bt, ctList);
            slFreeList(&ctList);
            }
        }
    fclose(f);
    }
slSort(&bacList, cmpBacTrack);

printStats();
return 0;
}
bool RangeUnitTest::runOnModule(Module & M) {
	MAX_BIT_INT = InterProceduralRA<Cousot>::getMaxBitWidth(M);
	Min = APInt::getSignedMinValue(MAX_BIT_INT);
	Max = APInt::getSignedMaxValue(MAX_BIT_INT);
	Zero = APInt(MAX_BIT_INT, 0, true);

	errs() << "Running unit tests for Range class!\n";
	// --------------------------- Shared Objects -------------------------//
	Range unknown(Min, Max, Unknown);
	Range empty(Min, Max, Empty);
	Range zero(Zero, Zero);
	Range infy(Min, Max);
	Range pos(Zero, Max);
	Range neg(Min, Zero);
	Range smallNeg(NEW_APINT(-17), Zero);
	Range smallPos(Zero, NEW_APINT(35));
	Range avgNeg(NEW_APINT(-27817), Zero);
	Range avgPos(Zero, NEW_APINT(182935));
	Range bigNeg(NEW_APINT(-281239847), Zero);
	Range bigPos(Zero, NEW_APINT(211821935));

	// -------------------------------- ADD --------------------------------//
	// [a, b] - [c, d] = [a + c, b + d]
	ASSERT_TRUE("ADD1", add, infy, infy, infy);
	ASSERT_TRUE("ADD2", add, zero, infy, infy);
	ASSERT_TRUE("ADD3", add, zero, zero, zero);
	ASSERT_TRUE("ADD4", add, neg, zero, neg);
	ASSERT_TRUE("ADD5", add, neg, infy, infy);
	ASSERT_TRUE("ADD6", add, neg, neg, neg);
	ASSERT_TRUE("ADD7", add, pos, zero, pos);
	ASSERT_TRUE("ADD8", add, pos, infy, infy);
	ASSERT_TRUE("ADD9", add, pos, neg, infy);
	ASSERT_TRUE("ADD10", add, pos, pos, pos);
	ASSERT_TRUE("ADD11", add, smallNeg, infy, infy);
	ASSERT_TRUE("ADD12", add, smallNeg, zero, smallNeg);
	ASSERT_TRUE("ADD13", add, smallNeg, pos, NEW_RANGE_MAX(-17));
	ASSERT_TRUE("ADD14", add, smallNeg, neg, neg);
	ASSERT_TRUE("ADD15", add, smallNeg, smallNeg, NEW_RANGE_N(-34,0));
	ASSERT_TRUE("ADD16", add, smallNeg, smallPos, NEW_RANGE_N(-17,35));
	ASSERT_TRUE("ADD17", add, smallNeg, avgNeg, NEW_RANGE_N(-27834,0));
	ASSERT_TRUE("ADD18", add, smallNeg, avgPos, NEW_RANGE_N(-17,182935));
	ASSERT_TRUE("ADD19", add, smallNeg, bigNeg, NEW_RANGE_N(-281239864,0));
	ASSERT_TRUE("ADD20", add, smallNeg, bigPos, NEW_RANGE_N(-17, 211821935));
	ASSERT_TRUE("ADD21", add, smallPos, infy, infy);
	ASSERT_TRUE("ADD22", add, smallPos, zero, smallPos);
	ASSERT_TRUE("ADD23", add, smallPos, pos, pos);
	ASSERT_TRUE("ADD24", add, smallPos, neg, NEW_RANGE_MIN(35));
	ASSERT_TRUE("ADD25", add, smallPos, smallPos, NEW_RANGE_N(0,70));
	ASSERT_TRUE("ADD26", add, smallPos, avgNeg, NEW_RANGE_N(-27817, 35));
	ASSERT_TRUE("ADD27", add, smallPos, avgPos, NEW_RANGE_N(0, 182970));
	ASSERT_TRUE("ADD28", add, smallPos, bigNeg, NEW_RANGE_N(-281239847, 35));
	ASSERT_TRUE("ADD29", add, smallPos, bigPos, NEW_RANGE_N(0, 211821970));
	ASSERT_TRUE("ADD30", add, avgNeg, infy, infy);
	ASSERT_TRUE("ADD31", add, avgNeg, zero, avgNeg);
	ASSERT_TRUE("ADD32", add, avgNeg, pos, NEW_RANGE_MAX(-27817));
	ASSERT_TRUE("ADD33", add, avgNeg, neg, neg);
	ASSERT_TRUE("ADD34", add, avgNeg, avgNeg, NEW_RANGE_N(-55634, 0));
	ASSERT_TRUE("ADD35", add, avgNeg, avgPos, NEW_RANGE_N(-27817, 182935));
	ASSERT_TRUE("ADD36", add, avgNeg, bigNeg, NEW_RANGE_N(-281267664, 0));
	ASSERT_TRUE("ADD37", add, avgNeg, bigPos, NEW_RANGE_N(-27817, 211821935));
	ASSERT_TRUE("ADD38", add, avgPos, infy, infy);
	ASSERT_TRUE("ADD39", add, avgPos, zero, avgPos);
	ASSERT_TRUE("ADD40", add, avgPos, pos, pos);
	ASSERT_TRUE("ADD41", add, avgPos, neg, NEW_RANGE_MIN(182935));
	ASSERT_TRUE("ADD42", add, avgPos, avgPos, NEW_RANGE_N(0, 365870));
	ASSERT_TRUE("ADD43", add, avgPos, bigNeg, NEW_RANGE_N(-281239847, 182935));
	ASSERT_TRUE("ADD44", add, avgPos, bigPos, NEW_RANGE_N(0, 212004870));
	ASSERT_TRUE("ADD45", add, bigNeg, infy, infy);
	ASSERT_TRUE("ADD46", add, bigNeg, zero, bigNeg);
	ASSERT_TRUE("ADD47", add, bigNeg, pos, NEW_RANGE_MAX(-281239847));
	ASSERT_TRUE("ADD48", add, bigNeg, neg, neg);
	ASSERT_TRUE("ADD49", add, bigNeg, bigNeg, NEW_RANGE_N(-562479694, 0));
	ASSERT_TRUE("ADD50", add, bigNeg, bigPos, NEW_RANGE_N(-281239847, 211821935));
	ASSERT_TRUE("ADD51", add, bigPos, infy, infy);
	ASSERT_TRUE("ADD52", add, bigPos, zero, bigPos);
	ASSERT_TRUE("ADD53", add, bigPos, pos, pos);
	ASSERT_TRUE("ADD54", add, bigPos, neg, NEW_RANGE_MIN(211821935));
	ASSERT_TRUE("ADD55", add, bigPos, bigPos, NEW_RANGE_N(0,423643870));

	// -------------------------------- SUB --------------------------------//
	// [a, b] - [c, d] = [a - d, b - c]
	ASSERT_TRUE("SUB1", sub, infy, infy, infy);
	ASSERT_TRUE("SUB2", sub, infy, zero, infy);
	ASSERT_TRUE("SUB3", sub, infy, pos, infy);
	ASSERT_TRUE("SUB4", sub, infy, neg, infy);
	ASSERT_TRUE("SUB5", sub, zero, zero, zero);
	ASSERT_TRUE("SUB6", sub, zero, infy, infy);
	ASSERT_TRUE("SUB7", sub, zero, pos, neg);
	ASSERT_TRUE("SUB8", sub, zero, neg, pos);
	ASSERT_TRUE("SUB9", sub, pos, zero, pos);
	ASSERT_TRUE("SUB10", sub, pos, infy, infy);
	ASSERT_TRUE("SUB11", sub, pos, neg, pos);
	ASSERT_TRUE("SUB12", sub, pos, pos, infy);
	ASSERT_TRUE("SUB13", sub, neg, zero, neg);
	ASSERT_TRUE("SUB14", sub, neg, infy, infy);
	ASSERT_TRUE("SUB15", sub, neg, neg, infy);
	ASSERT_TRUE("SUB16", sub, neg, pos, neg);

	// -------------------------------- MUL --------------------------------//
	//  [a, b] * [c, d] = [Min(a*c, a*d, b*c, b*d), Max(a*c, a*d, b*c, b*d)]
	ASSERT_TRUE("MUL1", mul, infy, infy, infy);
	ASSERT_TRUE("MUL2", mul, zero, infy, infy);
	ASSERT_TRUE("MUL3", mul, zero, zero, zero);
	ASSERT_TRUE("MUL4", mul, neg, zero, zero);
	ASSERT_TRUE("MUL5", mul, neg, infy, infy);
	ASSERT_TRUE("MUL6", mul, neg, neg, pos);
	ASSERT_TRUE("MUL7", mul, pos, zero, zero);
	ASSERT_TRUE("MUL8", mul, pos, infy, infy);
	ASSERT_TRUE("MUL9", mul, pos, neg, neg);
	ASSERT_TRUE("MUL10", mul, pos, pos, pos);
	ASSERT_TRUE("MUL11", mul, smallNeg, infy, infy);
	ASSERT_TRUE("MUL12", mul, smallNeg, zero, zero);
	ASSERT_TRUE("MUL13", mul, smallNeg, pos, neg);
	ASSERT_TRUE("MUL14", mul, smallNeg, neg, pos);
	ASSERT_TRUE("MUL15", mul, smallNeg, smallNeg, NEW_RANGE_N(0, 289));
	ASSERT_TRUE("MUL16", mul, smallNeg, smallPos, NEW_RANGE_N(-595, 0));
	ASSERT_TRUE("MUL17", mul, smallNeg, avgNeg, NEW_RANGE_N(0, 472889));
	ASSERT_TRUE("MUL18", mul, smallNeg, avgPos, NEW_RANGE_N(-3109895, 0));
	ASSERT_TRUE("MUL19", mul, smallNeg, bigNeg, NEW_RANGE_N(0, 486110103));
	ASSERT_TRUE("MUL20", mul, smallNeg, bigPos, NEW_RANGE_N(0, 693994401));
	ASSERT_TRUE("MUL21", mul, smallPos, infy, infy);
	ASSERT_TRUE("MUL22", mul, smallPos, zero, zero);
	ASSERT_TRUE("MUL23", mul, smallPos, pos, pos);
	ASSERT_TRUE("MUL24", mul, smallPos, neg, neg);
	ASSERT_TRUE("MUL25", mul, smallPos, smallPos, NEW_RANGE_N(0, 1225));
	ASSERT_TRUE("MUL26", mul, smallPos, avgNeg, NEW_RANGE_N(-973595, 0));
	ASSERT_TRUE("MUL27", mul, smallPos, avgPos, NEW_RANGE_N(0, 6402725));
	ASSERT_TRUE("MUL28", mul, smallPos, bigNeg, NEW_RANGE_N(-1253460053, 0));
	ASSERT_TRUE("MUL29", mul, smallPos, bigPos, NEW_RANGE_N(-1176166867, 0));
	ASSERT_TRUE("MUL30", mul, avgNeg, infy, infy);
	ASSERT_TRUE("MUL31", mul, avgNeg, zero, zero);
	ASSERT_TRUE("MUL32", mul, avgNeg, pos, neg);
	ASSERT_TRUE("MUL33", mul, avgNeg, neg, pos);
	ASSERT_TRUE("MUL34", mul, avgNeg, avgNeg, NEW_RANGE_N(0, 773785489));
	ASSERT_TRUE("MUL35", mul, avgNeg, avgPos, NEW_RANGE_N(-793735599, 0));
	ASSERT_TRUE("MUL38", mul, avgPos, infy, infy);
	ASSERT_TRUE("MUL39", mul, avgPos, zero, zero);
	ASSERT_TRUE("MUL40", mul, avgPos, pos, pos);
	ASSERT_TRUE("MUL41", mul, avgPos, neg, neg);
	ASSERT_TRUE("MUL45", mul, bigNeg, infy, infy);
	ASSERT_TRUE("MUL46", mul, bigNeg, zero, zero);
	ASSERT_TRUE("MUL47", mul, bigNeg, pos, neg);
	ASSERT_TRUE("MUL48", mul, bigNeg, neg, pos);
	ASSERT_TRUE("MUL51", mul, bigPos, infy, infy);
	ASSERT_TRUE("MUL52", mul, bigPos, zero, zero);
	ASSERT_TRUE("MUL53", mul, bigPos, pos, pos);
	ASSERT_TRUE("MUL54", mul, bigPos, neg, neg);

	// -------------------------------- DIV --------------------------------//
	// [a, b] / [c, d] = [Min(a/c, a/d, b/c, b/d), Max(a/c, a/d, b/c, b/d)]
	ASSERT_TRUE("UDIV1", udiv, infy, infy, unknown);
	ASSERT_TRUE("UDIV2", udiv, infy, zero, unknown);
	ASSERT_TRUE("UDIV3", udiv, infy, pos, unknown);
	ASSERT_TRUE("UDIV4", udiv, infy, neg, unknown);
	ASSERT_TRUE("UDIV5", udiv, infy, smallNeg, unknown);
	ASSERT_TRUE("UDIV6", udiv, infy, smallPos, unknown);
	ASSERT_TRUE("UDIV7", udiv, infy, avgNeg, unknown);
	ASSERT_TRUE("UDIV8", udiv, infy, avgPos, unknown);
	ASSERT_TRUE("UDIV9", udiv, infy, bigNeg, unknown);
	ASSERT_TRUE("UDIV10", udiv, infy, bigPos, unknown);
	ASSERT_TRUE("UDIV11", udiv, zero, zero, unknown);
	ASSERT_TRUE("UDIV12", udiv, zero, infy, zero);
	ASSERT_TRUE("UDIV13", udiv, zero, pos, unknown);
	ASSERT_TRUE("UDIV14", udiv, zero, neg, unknown);
	ASSERT_TRUE("UDIV15", udiv, zero, smallNeg, unknown);
	ASSERT_TRUE("UDIV16", udiv, zero, smallPos, unknown);
	ASSERT_TRUE("UDIV17", udiv, zero, avgNeg, unknown);
	ASSERT_TRUE("UDIV18", udiv, zero, avgPos, unknown);
	ASSERT_TRUE("UDIV19", udiv, zero, bigNeg, unknown);
	ASSERT_TRUE("UDIV20", udiv, zero, bigPos, unknown);
	ASSERT_TRUE("UDIV21", udiv, pos, zero, unknown);
	ASSERT_TRUE("UDIV22", udiv, pos, infy, unknown);
	ASSERT_TRUE("UDIV23", udiv, pos, neg, unknown);
	ASSERT_TRUE("UDIV24", udiv, pos, pos, unknown);
	ASSERT_TRUE("UDIV25", udiv, pos, smallNeg, unknown);
	ASSERT_TRUE("UDIV26", udiv, pos, smallPos, unknown);
	ASSERT_TRUE("UDIV27", udiv, pos, avgNeg, unknown);
	ASSERT_TRUE("UDIV28", udiv, pos, avgPos, unknown);
	ASSERT_TRUE("UDIV29", udiv, pos, bigNeg, unknown);
	ASSERT_TRUE("UDIV30", udiv, pos, bigPos, unknown);
	ASSERT_TRUE("UDIV31", udiv, neg, zero, unknown);
	ASSERT_TRUE("UDIV32", udiv, neg, infy, unknown);
	ASSERT_TRUE("UDIV33", udiv, neg, neg, unknown);
	ASSERT_TRUE("UDIV34", udiv, neg, pos, unknown);
	ASSERT_TRUE("UDIV35", udiv, neg, smallNeg, unknown);
	ASSERT_TRUE("UDIV36", udiv, neg, smallPos, unknown);
	ASSERT_TRUE("UDIV37", udiv, neg, avgNeg, unknown);
	ASSERT_TRUE("UDIV38", udiv, neg, avgPos, unknown);
	ASSERT_TRUE("UDIV39", udiv, neg, bigNeg, unknown);
	ASSERT_TRUE("UDIV40", udiv, neg, bigPos, unknown);
	ASSERT_TRUE("UDIV41", udiv, smallNeg, infy, unknown);
	ASSERT_TRUE("UDIV42", udiv, smallNeg, zero, unknown);
	ASSERT_TRUE("UDIV43", udiv, smallNeg, pos, unknown);
	ASSERT_TRUE("UDIV44", udiv, smallNeg, neg, unknown);
	ASSERT_TRUE("UDIV45", udiv, smallNeg, smallNeg, unknown);
	ASSERT_TRUE("UDIV46", udiv, smallNeg, smallPos, unknown);
	ASSERT_TRUE("UDIV47", udiv, smallNeg, avgNeg, unknown);
	ASSERT_TRUE("UDIV48", udiv, smallNeg, avgPos, unknown);
	ASSERT_TRUE("UDIV49", udiv, smallNeg, bigNeg, unknown);
	ASSERT_TRUE("UDIV50", udiv, smallNeg, bigPos, unknown);
	ASSERT_TRUE("UDIV51", udiv, smallPos, infy, unknown);
	ASSERT_TRUE("UDIV52", udiv, smallPos, zero, unknown);
	ASSERT_TRUE("UDIV53", udiv, smallPos, pos, unknown);
	ASSERT_TRUE("UDIV54", udiv, smallPos, neg, unknown);
	ASSERT_TRUE("UDIV55", udiv, smallPos, smallNeg, unknown);
	ASSERT_TRUE("UDIV56", udiv, smallPos, smallPos, unknown);
	ASSERT_TRUE("UDIV57", udiv, smallPos, avgNeg, unknown);
	ASSERT_TRUE("UDIV58", udiv, smallPos, avgPos, unknown);
	ASSERT_TRUE("UDIV59", udiv, smallPos, bigNeg, unknown);
	ASSERT_TRUE("UDIV60", udiv, smallPos, bigPos, unknown);
	ASSERT_TRUE("UDIV61", udiv, avgNeg, infy, unknown);
	ASSERT_TRUE("UDIV62", udiv, avgNeg, zero, unknown);
	ASSERT_TRUE("UDIV63", udiv, avgNeg, pos, unknown);
	ASSERT_TRUE("UDIV64", udiv, avgNeg, neg, unknown);
	ASSERT_TRUE("UDIV65", udiv, avgNeg, smallNeg, unknown);
	ASSERT_TRUE("UDIV66", udiv, avgNeg, smallPos, unknown);
	ASSERT_TRUE("UDIV67", udiv, avgNeg, avgNeg, unknown);
	ASSERT_TRUE("UDIV68", udiv, avgNeg, avgPos, unknown);
	ASSERT_TRUE("UDIV69", udiv, avgNeg, bigNeg, unknown);
	ASSERT_TRUE("UDIV70", udiv, avgNeg, bigPos, unknown);
	ASSERT_TRUE("UDIV71", udiv, avgPos, infy, unknown);
	ASSERT_TRUE("UDIV72", udiv, avgPos, zero, unknown);
	ASSERT_TRUE("UDIV73", udiv, avgPos, pos, unknown);
	ASSERT_TRUE("UDIV74", udiv, avgPos, neg, unknown);
	ASSERT_TRUE("UDIV75", udiv, avgPos, smallNeg, unknown);
	ASSERT_TRUE("UDIV76", udiv, avgPos, smallPos, unknown);
	ASSERT_TRUE("UDIV77", udiv, avgPos, avgNeg, unknown);
	ASSERT_TRUE("UDIV78", udiv, avgPos, avgPos, unknown);
	ASSERT_TRUE("UDIV79", udiv, avgPos, bigNeg, unknown);
	ASSERT_TRUE("UDIV80", udiv, avgPos, bigPos, unknown);
	ASSERT_TRUE("UDIV81", udiv, bigNeg, infy, unknown);
	ASSERT_TRUE("UDIV82", udiv, bigNeg, zero, unknown);
	ASSERT_TRUE("UDIV83", udiv, bigNeg, pos, unknown);
	ASSERT_TRUE("UDIV84", udiv, bigNeg, neg, unknown);
	ASSERT_TRUE("UDIV85", udiv, bigNeg, smallNeg, unknown);
	ASSERT_TRUE("UDIV86", udiv, bigNeg, smallPos, unknown);
	ASSERT_TRUE("UDIV87", udiv, bigNeg, avgNeg, unknown);
	ASSERT_TRUE("UDIV88", udiv, bigNeg, avgPos, unknown);
	ASSERT_TRUE("UDIV89", udiv, bigNeg, bigNeg, unknown);
	ASSERT_TRUE("UDIV90", udiv, bigNeg, bigPos, unknown);
	ASSERT_TRUE("UDIV91", udiv, bigPos, infy, unknown);
	ASSERT_TRUE("UDIV92", udiv, bigPos, zero, unknown);
	ASSERT_TRUE("UDIV93", udiv, bigPos, pos, unknown);
	ASSERT_TRUE("UDIV94", udiv, bigPos, neg, unknown);
	ASSERT_TRUE("UDIV95", udiv, bigPos, smallNeg, unknown);
	ASSERT_TRUE("UDIV96", udiv, bigPos, smallPos, unknown);
	ASSERT_TRUE("UDIV97", udiv, bigPos, avgNeg, unknown);
	ASSERT_TRUE("UDIV98", udiv, bigPos, avgPos, unknown);
	ASSERT_TRUE("UDIV99", udiv, bigPos, bigNeg, unknown);
	ASSERT_TRUE("UDIV100", udiv, bigPos, bigPos, unknown);

	printStats();
	return true;
}
예제 #20
0
void PredictLeague::printResultsHDL() {
	printStats(league->getGames(1, league->getLastRound()));
	//printPredictedStats(getGameRatings());
}
void *MeldInterpretScheduler::startPaused(/*void *param*/) {

    int seed = 500;
    srand (seed);
    bool hasProcessed = false;

    // 1) world ready
    // 2) user start order
    int nbSemWait = 1;

    //usleep(1000000);
    OUTPUT << "\033[1;33mScheduler Mode :" << schedulerMode << "\033[0m" << endl;
#ifndef TEST_DETER
    if (MeldInterpretVM::isInDebuggingMode()) {
        // 3) Debugger "run"
        nbSemWait = 3;
    }
    for (int i = 0; i < nbSemWait; i++) {
        SemWaitOrReadDebugMessage();
    }
#else
    sem_schedulerStart->wait();
    schedulerMode = SCHEDULER_MODE_FASTEST;
#endif
    state = RUNNING;
    //checkForReceivedVMCommands();
    multimap<Time, EventPtr>::iterator first, tmp;
    EventPtr pev;
	auto systemStartTime = get_time::now();
    auto pausedTime = systemStartTime - systemStartTime; // zero by default
	cout << "\033[1;33m" << "Scheduler : start order received " << 0 << "\033[0m" << endl;

    switch (schedulerMode) {
    case SCHEDULER_MODE_FASTEST:
        OUTPUT << "fastest mode scheduler\n" << endl;
        //MeldInterpretDebugger::print("Simulation starts in deterministic mode");
        while (state != ENDED) {
            do {
                  while (!eventsMap.empty()  || schedulerLength == SCHEDULER_LENGTH_INFINITE) {
                        hasProcessed = true;
                        // lock();
                        first = eventsMap.begin();
                        pev = (*first).second;
                        currentDate = pev->date;
                        pev->consume();
                        StatsCollector::getInstance().incEventsCount();
                        eventsMap.erase(first);
                        eventsMapSize--;
                        // unlock();
                        if (state == PAUSED) {
                              if (MeldInterpretVM::isInDebuggingMode()) {
                              //getDebugger()->handleBreakAtTimeReached(currentDate);
                              } else {
                                    sem_schedulerStart->wait();
                              }
                              setState(RUNNING);
                        }

                        // Check that we have not reached the maximum simulation date, if there is one
                        if (currentDate > maximumDate) {
                            cout << "\033[1;33m" << "Scheduler : maximum simulation date (" << maximumDate
                                 << ") has been reached. Terminating..." << "\033[0m" << endl;
                            break;
                        }

                        //checkForReceivedVMCommands();
                  }
                  OUTPUT << "EventMap is empty" << endl;
                  // PTHY: Equilibrium doesn't seem to be working, use SCHEDULER_LENGTH_INFINITE
                  //       to keep looping
                  if (eventsMap.empty() && schedulerLength != SCHEDULER_LENGTH_INFINITE) {
                      state = ENDED;
                      break;
                  }

                  if (terminate.load()) {
                      break;
                  }
                //checkForReceivedVMCommands();
            } while (!MeldInterpretVM::equilibrium() || !eventsMap.empty());

            if(hasProcessed) {
                hasProcessed = false;
                ostringstream s;
                s << "Equilibrium reached at "<< now() << "us ...";
                //MeldInterpretDebugger::print(s.str(), false);
                /*if (getSimulator()->testMode) {
                  BlinkyBlocks::getWorld()->dump();
                  stop(0);
                  return 0;
                  }*/
                if (MeldInterpretVM::isInDebuggingMode()) {
                    //getDebugger()->handlePauseRequest();
                }
            }

            //checkForReceivedVMCommands();
        }
#ifdef TEST_DETER
        getWorld()->killAllVMs();
        exit(0);
#endif
        break;

    case SCHEDULER_MODE_REALTIME: 
        OUTPUT << "Realtime mode scheduler\n" << endl;
        //MeldInterpretDebugger::print("Simulation starts in real time mode");
	    while((state != ENDED && !eventsMap.empty()) || schedulerLength == SCHEDULER_LENGTH_INFINITE) {
	        auto systemCurrentTime = get_time::now() - pausedTime;
	    	auto systemCurrentTimeMax = systemCurrentTime - systemStartTime;
            // currentDate = systemCurrentTimeMax;
            //checkForReceivedVMCommands();
            // while (true) {
            //     // Lock from here, to be sure that the element
            //     // is not destroyed in another thread
            //     // (previously the graphic interface was doing
            //     // it).
            //     lock();
            //     if (eventsMap.empty()) {
            //         unlock();
            //         break;
            //     }
            //     first=eventsMap.begin();
            //     pev = (*first).second;
            //     if(pev->date > systemCurrentTimeMax) {
            //         unlock();
            //         break;
            //     }
            //     currentDate = pev->date;
            //     pev->consume();
            //     eventsMap.erase(first);
            //     eventsMapSize--;
            //     unlock();
            //     //cout << "check to send" << endl;
            //     //checkForReceivedVMCommands();
            //     //cout << "ok" << endl;
            // }
            
			if (!eventsMap.empty()) {
				first=eventsMap.begin();
				pev = (*first).second;
				while (!eventsMap.empty() && pev->date <= chrono::duration_cast<us>(systemCurrentTimeMax).count()) {
					first=eventsMap.begin();
					pev = (*first).second;
					currentDate = pev->date;
					//lock();
					pev->consume();
                    StatsCollector::getInstance().incEventsCount();
					//unlock();
					eventsMap.erase(first);
					eventsMapSize--;
				}
			}

			if (!eventsMap.empty()) {
				//ev = *(listeEvenements.begin());
				first=eventsMap.begin();
				pev = (*first).second;
			}

            if (state == PAUSED) {
                cout << "paused" << endl;
                auto pauseBeginning = get_time::now();
                SemWaitOrReadDebugMessage();
                setState(RUNNING);
                pausedTime = get_time::now() - pauseBeginning;
            }

			if (!eventsMap.empty() || schedulerLength == SCHEDULER_LENGTH_INFINITE) {
				std::chrono::milliseconds timespan(5);
				std::this_thread::sleep_for(timespan);
			}

            
			if (terminate.load()) {
				break;
			}
        }
    break;
    default:
        OUTPUT << "ERROR : Scheduler mode not recognized !!" << endl;
    }

    auto systemStopTime = get_time::now();
	auto elapsedTime = systemStopTime - systemStartTime;

	cout << "\033[1;33m" << "Scheduler end : " << chrono::duration_cast<us>(elapsedTime).count() << "\033[0m" << endl;

	pev.reset();

	StatsCollector::getInstance().updateElapsedTime(currentDate, chrono::duration_cast<us>(elapsedTime).count());
	StatsCollector::getInstance().setLivingCounters(Event::getNbLivingEvents(), Message::getNbMessages());
	StatsCollector::getInstance().setEndEventsQueueSize(eventsMap.size());

	// if simulation is a regression testing run, export configuration before leaving
	if (Simulator::regrTesting && !terminate.load())
		getWorld()->exportConfiguration();
	
	// if autoStop is enabled, terminate simulation
	if (willAutoStop() && !terminate.load())
		glutLeaveMainLoop();

	printStats();

	terminate.store(true);
	
    return(NULL);
}
예제 #22
0
/*
 * findAndLogAllPossibleLegs has the same search algorithm as findAllPossibleLegs. However, the requirement
 * that all the legs be logged requires a more sophisticated means of parallelization in order to do a
 * reduction of the solutions when all the threads are done.
 */
int findAndLogAllPossibleLegs(Graph *graph, SearchOptions *options)
{
    int i, j, k;
    int found = 0;
    int searches = 0;
    double tick, tock;
    int hours, min;
    double sec;
    int maxThreads = 1;
    NodeVecVec **lastingResults;
    Graph *optimizedGraph = NULL;
    char timeStr[50];

    /* A little bit of error checking */
    if ( !graph )
        return 0;

    tick = currentTime();
    fprintf(stderr, "Immediately before parallel\n" );

    #pragma omp parallel private(i,j,k) shared(graph,maxThreads,lastingResults) reduction(+:found) reduction(+:searches)
    {
        int myThread = omp_get_thread_num();
        NodeVecVec *myResults = NULL;

        #pragma omp single
        {
            maxThreads = omp_get_num_threads();
            options->multiThreaded = maxThreads > 1;
#ifdef DEBUG
            printf( "%d total threads, this one is %d\n", maxThreads, myThread );
#endif
            lastingResults = malloc((maxThreads+1) * sizeof(NodeVecVec*) );
            lastingResults[maxThreads] = 0; /* Null terminated to avoid having to keep track of bitsNeeded */
        }

        #pragma omp critical
        {
            lastingResults[myThread] = NodeVecVec_new(64); /* Arbitrary - multiple of 8, eventually cache line aligned... */
            myResults = lastingResults[myThread];
        }

        #pragma omp single
        {
            printf ("Immediately before nested for's\n");
        }

        #pragma omp for collapse(2)
        for ( i = 0; i < graph->systemCallMap->contentSize; ++i )
        {
            for ( j = 0; j < graph->systemCallMap->contentSize; ++j )
            {
                ++searches;
                for (k = 0; k < graph->systemCallMap->vector[i]->nodes->contentSize; ++k)
                {
                    char *fullSignature[3] = { NULL, NULL, NULL };
                    int fullIntSignature[3] = { 0, 0, -1 };
                    fullSignature[0] = graph->systemCallMap->vector[i]->label;
                    fullSignature[1] = graph->systemCallMap->vector[j]->label;
                    fullIntSignature[0] = i;
                    fullIntSignature[1] = j;
                    NodePtrVec *result = NodePtrVec_new(16);
                    Bitfield *visited = Bitfield_new(graph->totalNodes);
#ifdef DEBUG
                    printf( "Searching for %s(%d) ~~~> %s\n", fullSignature[0],
                            graph->systemCallMap->vector[i]->nodes->vector[k]->id,
                            fullSignature[1]);
#endif
                    findAndRecordAllPaths( graph->systemCallMap->vector[i]->nodes->vector[k], &fullSignature[1],
                            &fullIntSignature[1], result, visited, myResults, options );
                    Bitfield_delete(visited);
                    if ( result )
                        NodePtrVec_delete( result );
                } // end of for (k)... fork? heh.
            } // end of for (j)
        } // end of for (i)

        found = myResults->contentSize;
    }

    tock = currentTime();
    sec = tock-tick;
    hours = (int)sec/3600;
    sec = fmod( sec, 3600.0 );
    min = (int)sec/60;
    sec = fmod( sec, 60.0 );
    printf ( "\n\n%d found for %d searches. Overall Time: %d:%d:%2.3f\n",
            found, searches, hours, min, sec );
    timeStr[0] = '\0'; /* just in case sprintf doesn't do what we want. */
    sprintf ( timeStr, "%02d:%02d:%02.3f", hours, min, sec );
    YAMLWriteInt("Signatures Found", found);
    YAMLWriteString("Search Time", timeStr);

#ifdef DEBUG
    printf ("max threads still:%d\n", maxThreads);
    for ( i = 0; i < maxThreads; ++i )
    {
        printf ( "printing out thread %d result - %d long\n", i, lastingResults[i]->contentSize );
        for ( j = 0; j < lastingResults[i]->contentSize; ++j )
        {
            printf("\t");
            printStack( lastingResults[i]->vector[j] );
            printf("\n");
        }
    }
#endif

    /* At some point, we will want to use the FullPath argument and pass it along to
     * buildGraphFromPaths. Until then, however, we're only going to build the most
     * minimal graph possible.
     */
    if ( options->writeOutputFile && options->outputFile )
    {
        optimizedGraph = buildGraphFromPaths(lastingResults, options->buildType);
        exportGraph(optimizedGraph, options->outputFile);
    }

    if ( options->doStatistics && !options->multiThreaded )
        printStats();

    return( found );
}
예제 #23
0
파일: whosh.cpp 프로젝트: osm-spline/whosh
 void callback_final() {
     printStats();
     std::cerr << std::endl << "Max UserID was: " << user_count << std::endl;
 }
예제 #24
0
/*
 * function: main()
 */
int main(int argc, char *argv[]) {
    sgs_buffer *buf;
    uint8_t content[100];
    uint8_t content2[100];
    int result;
    size_t i;
  
    for (i=0; i < sizeof(content); i++)
        content[i] = i;
  
    for (i=0; i < sizeof(content2); i++)
        content2[i] = 99;
  
    buf = sgs_buffer_create(10);
    if (buf == NULL) { perror("new() failed.\n"); exit(-1); }
  
    result = sgs_buffer_peek(buf, content2, 1);
    printf("PEEK(1) = %d  \t|  ", result);
    printStats(buf);
  
    result = sgs_buffer_write(buf, content, 5);
    printf("WRITE(5) = %d  \t|  ", result);
    printStats(buf);
  
    result = sgs_buffer_peek(buf, content2, 2);
    printf("PEEK(2) = %d  \t|  ", result);
    printStats(buf);
    printArr("results", content2, 10);
  
    result = sgs_buffer_read(buf, content2, 3);
    printf("READ(3) = %d  \t|  ", result);
    printStats(buf);
    printArr("results", content2, 10);
  
    result = sgs_buffer_read(buf, content2, 3);
    printf("READ(3) = %d  \t|  ", result);
    printStats(buf);
  
    printf("internal: ");
    sgs_buffer_dump(buf);
    printf("\n");
  
    result = sgs_buffer_write(buf, content, 9);
    printf("WRITE(9) = %d  \t|  ", result);
    printStats(buf);
  
    result = sgs_buffer_write(buf, content, 8);
    printf("WRITE(8) = %d  \t|  ", result);
    printStats(buf);
  
    printf("internal: ");
    sgs_buffer_dump(buf);
    printf("\n");
  
    result = sgs_buffer_read(buf, content2, 11);
    printf("READ(11) = %d  \t|  ", result);
    printStats(buf);
  
    result = sgs_buffer_read(buf, content2, 10);
    printf("READ(10) = %d  \t|  ", result);
    printStats(buf);
    printArr("results", content2, 10);
  
    sgs_buffer_destroy(buf);
  
    printf("Goodbye!\n");
  
    return 0;
}
예제 #25
0
파일: Main.C 프로젝트: pmatos/maxsatzilla
static void SIGINT_handler(int signum) {
    reportf("\n"); reportf("*** INTERRUPTED ***\n");
    printStats(*solver);
    reportf("\n"); reportf("*** INTERRUPTED ***\n");
    exit(1); }
예제 #26
0
Foam::octree<Type>::octree
(
    const treeBoundBox& octreeBb,
    const Type& shapes,
    const label minNLevels,
    const scalar maxLeafRatio,
    const scalar maxShapeRatio
)
:
    topNode_(new treeNode<Type>(octreeBb)),
    shapes_(shapes),
    octreeBb_(octreeBb),
    maxLeafRatio_(maxLeafRatio),
    maxShapeRatio_(maxShapeRatio),
    minNLevels_(minNLevels),
    deepestLevel_(0),
    nEntries_(0),
    nNodes_(0),
    nLeaves_(0),
    endIter_(*this, -1),
    endConstIter_(*this, -1)
{
    cpuTime timer;

    setNodes(nNodes() + 1);

    const label nShapes = shapes_.size();

    labelList indices(nShapes);
    for (label i = 0; i < nShapes; i++)
    {
        indices[i] = i;
    }

    // Create initial level (0) of subLeaves
    if (debug & 1)
    {
        Pout<< "octree : --- Start of Level " << deepestLevel_
            << " ----" << endl;
    }
    topNode_->distribute(0, *this, shapes_, indices);

    if (debug & 1)
    {
        printStats(Pout);
        Pout<< "octree : --- End of Level " << deepestLevel_
            << " ----" << endl;
    }

    // Breadth first creation of tree
    // Stop if: - level above minlevel and
    //                - less than so many cells per endpoint
    //                  (so bottom level is fine enough)
    //                - every shape mentioned in only so many
    //                  leaves. (if shape bb quite big it will end up
    //                  in lots of leaves).
    //          - no change in number of leaves
    //            (happens if leafs fine enough)
    // This guarantees that tree
    //  - is fine enough (if minLevel > 0)
    //  - has some guaranteed maximum size (maxShapeRatio)

    label oldNLeaves = -1;  // make test below pass first time.
    deepestLevel_ = 1;
    while
    (
        (deepestLevel_ <= minNLevels_)
     || (
            (nEntries() > maxLeafRatio * nLeaves())    // shapes per leaf
         && (nEntries() < maxShapeRatio * nShapes)     // entries per shape
        )
    )
    {
        if (deepestLevel_ >= maxNLevels)
        {
            if (debug & 1)
            {
                Pout<< "octree : exiting since maxNLevels "
                    << maxNLevels << " reached" << endl;
            }
            break;
        }

        if (oldNLeaves == nLeaves())
        {
            if (debug & 1)
            {
                Pout<< "octree : exiting since nLeaves does not change"
                    << endl;
            }
            break;
        }
        if (debug & 1)
        {
            Pout<< "octree : --- Start of Level " << deepestLevel_
                << " ----" << endl;
        }

        oldNLeaves = nLeaves();

        topNode_->redistribute
        (
            1,
            *this,
            shapes_,
            deepestLevel_
        );

        if (debug & 1)
        {
            printStats(Pout);

            Pout<< "octree : --- End of Level " << deepestLevel_
                << " ----" << endl;
        }

        deepestLevel_++;
    }


    if (debug & 1)
    {
        Pout<< "octree : Constructed octree in = "
        << timer.cpuTimeIncrement()
        << " s\n" << endl << endl;
    }

    // Set volume type of non-treeleaf nodes.
    topNode_->setSubNodeType(0, *this, shapes_);

    if (debug & 1)
    {
        Pout<< "octree : Added node information to octree in  = "
        << timer.cpuTimeIncrement()
        << " s\n" << endl << endl;
    }
}
예제 #27
0
파일: console.c 프로젝트: gwicks/craps-gba
//---------------------------------------------------------------------------------
// Program entry point
//---------------------------------------------------------------------------------
int main(void) {
//---------------------------------------------------------------------------------

	// the vblank interrupt must be enabled for VBlankIntrWait() to work
	// since the default dispatcher handles the bios flags no vblank handler
	// is required
	int gamecount = 1;
	
	
	irqInit();
	irqEnable(IRQ_VBLANK);

	//consoleDemoInit();
	consoleInit(	0,		/* charbase */
					4,		/* mapbase */
					0,		/* background number */
					NULL,	/* font */
					0, 		/* font size */
					15		/* 16 color palette */);
					
	BG_COLORS[0]=RGB8(0,0,0);
	BG_COLORS[241]=RGB5(31,31,31);

	SetMode(MODE_0 | BG0_ON);


	// ansi escape sequence to clear screen and home cursor
	// /x1b[line;columnH
	iprintf("\x1b[2J");

	// ansi escape sequence to set print co-ordinates
	// /x1b[line;columnH


	// ansi escape sequence to move cursor up
	// /x1b[linesA


	// ansi escape sequence to move cursor left
	// /x1b[columnsD


	// ansi escape sequence to move cursor down
	// /x1b[linesB
	

	// ansi escape sequence to move cursor right
	// /x1b[columnsC
	
	
	iprintf("\x1b[0;0HGames: %d",gamecount);

	while (1) {
		VBlankIntrWait();
		scanKeys();

		int keys_pressed = keysDown();
		int keys_released = keysUp();
		
		if (keys_pressed & KEY_UP)
		{
			gamecount = gamecount + 1;
			iprintf("\x1b[0;0H             ");
			iprintf("\x1b[0;0HGames: %d",gamecount);
		}
		if (keys_pressed & KEY_DOWN)
		{
			if (gamecount > 1)
			{
			gamecount = gamecount - 1;
			iprintf("\x1b[0;0H             ");
			iprintf("\x1b[0;0HGames: %d",gamecount);
			}
		}
		if (keys_pressed & KEY_A)
		{
			wincount = 0;
			rollstats[0] = 0;
			rollstats[1] = 0;
			rollstats[2] = 0;
			rollstats[3] = 0;
			rollstats[4] = 0;
			rollstats[5] = 0;
			simulateCraps(gamecount);
			iprintf("\x1b[1;0HWe simulated %d games",gamecount);
			iprintf("\x1b[2;0HYou won %d games",wincount);
			printStats();
		}
		
		
	}
}
예제 #28
0
void kmp_stats_output_module::outputStats(const char* heading) 
{
    statistic allStats[TIMER_LAST];
    statistic allCounters[COUNTER_LAST];

    // stop all the explicit timers for all threads
    windupExplicitTimers();

    FILE * eventsOut;
    FILE * statsOut = outputFileName ? fopen (outputFileName, "a+") : stderr;

    if (eventPrintingEnabled()) {
        eventsOut = fopen(eventsFileName, "w+");
    }

    if (!statsOut)
        statsOut = stderr;

    fprintf(statsOut, "%s\n",heading);
    // Accumulate across threads.
    kmp_stats_list::iterator it;
    for (it = __kmp_stats_list.begin(); it != __kmp_stats_list.end(); it++) {
        int t = (*it)->getGtid();
        // Output per thread stats if requested.
        if (perThreadPrintingEnabled()) {
            fprintf (statsOut, "Thread %d\n", t);
            printStats(statsOut, (*it)->getTimers(), true);
            printCounters(statsOut, (*it)->getCounters());
            fprintf(statsOut,"\n");
        }
        // Output per thread events if requested.
        if (eventPrintingEnabled()) {
            kmp_stats_event_vector events = (*it)->getEventVector();
            printEvents(eventsOut, &events, t);
        }

        for (int s = 0; s<TIMER_LAST; s++) {
            // See if we should ignore this timer when aggregating
            if ((timeStat::masterOnly(timer_e(s)) && (t != 0)) || // Timer is only valid on the master and this thread is a worker
                (timeStat::workerOnly(timer_e(s)) && (t == 0)) || // Timer is only valid on a worker and this thread is the master
                timeStat::synthesized(timer_e(s))                 // It's a synthesized stat, so there's no raw data for it.
               )            
            {
                continue;
            }

            statistic * threadStat = (*it)->getTimer(timer_e(s));
            allStats[s] += *threadStat;
        }

        // Special handling for synthesized statistics.
        // These just have to be coded specially here for now. 
        // At present we only have a few: 
        // The total parallel work done in each thread.
        // The variance here makes it easy to see load imbalance over the whole program (though, of course,
        // it's possible to have a code with awful load balance in every parallel region but perfect load
        // balance oever the whole program.)
        // The time spent in barriers in each thread.
        allStats[TIMER_Total_work].addSample ((*it)->getTimer(TIMER_OMP_work)->getTotal());

        // Time in explicit barriers.
        allStats[TIMER_Total_barrier].addSample ((*it)->getTimer(TIMER_OMP_barrier)->getTotal());

        for (int c = 0; c<COUNTER_LAST; c++) {
            if (counter::masterOnly(counter_e(c)) && t != 0)
                continue;
            allCounters[c].addSample ((*it)->getCounter(counter_e(c))->getValue());
        }
    }

    if (eventPrintingEnabled()) {
        printPloticusFile();
        fclose(eventsOut);
    }

    fprintf (statsOut, "Aggregate for all threads\n");
    printStats (statsOut, &allStats[0], true);
    fprintf (statsOut, "\n");
    printStats (statsOut, &allCounters[0], false);

    if (statsOut != stderr)
        fclose(statsOut);

}
예제 #29
0
void printStatsTask() {
  while (getchar() && !finished) printStats();
}
예제 #30
0
void copyCompress(const char *from, const char *to, size32_t rowsize, bool fast, bool flzstrm, bool stats)
{
    Owned<IFile> srcfile = createIFile(from);
    Owned<IFileIO> baseio = srcfile->open(IFOread);
    if (!baseio) {
        printf("ERROR: could not open '%s' for read\n",from);
        doexit(3);
    }
    Owned<ICompressedFileIO> cmpio = createCompressedFileReader(baseio);
    Owned<IFileIOStream>  flzstrmsrc = cmpio?NULL:createFastLZStreamRead(baseio);
    bool plaincopy = false;
    IFileIO *srcio = NULL;
    if (cmpio) {
        srcio = cmpio;
        if (rowsize&&(cmpio->recordSize()==rowsize))
            plaincopy = true;
        else if (!rowsize) {
            if (fast&&(cmpio->method()==COMPRESS_METHOD_FASTLZ))
                plaincopy = true;
            else if (!fast&&(cmpio->method()==COMPRESS_METHOD_LZW))
                plaincopy = true;
        }
    }
    else if (flzstrmsrc) {
        if (flzstrm)
            plaincopy = true;
    }
    else
        srcio = baseio; 
    if (plaincopy) {
        cmpio.clear();
        srcio = baseio.get(); 
    }
    Owned<IFile> dstfile = createIFile(to);
    StringBuffer fulldst;
    if (dstfile->isDirectory()==foundYes) {
        dstfile.clear();
        addPathSepChar(fulldst.append(to)).append(pathTail(from));
        to = fulldst.str();
        dstfile.setown(createIFile(to));
    }

    if (dstfile->exists()) {
        printf("ERROR: file '%s' already exists\n",to);
        doexit(4);
    }
    unsigned start;
    unsigned startu;
    if (stats) {
         start = msTick();
         startu = usTick();
    }
    Owned<IFileIO> dstio;
    Owned<IFileIOStream>  flzstrmdst;
    if (plaincopy||flzstrm) {
        dstio.setown(dstfile->open(IFOcreate));
        if (dstio&&!plaincopy)
            flzstrmdst.setown(createFastLZStreamWrite(dstio));
    }
    else 
        dstio.setown(createCompressedFileWriter(dstfile,rowsize,false,true,NULL,fast));

    if (!dstio) {
        printf("ERROR: could not open '%s' for write\n",to);
        doexit(5);
    }
#ifdef __linux__
    // this is not really needed in windows - if it is we will have to
    // test the file extension - .exe, .bat

    struct stat info;
    if (stat(from, &info) == 0)  // cannot fail - exception would have been thrown above
        dstfile->setCreateFlags(info.st_mode&(S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR|S_IWGRP|S_IWOTH|S_IXUSR|S_IXGRP|S_IXOTH));
#endif
    MemoryAttr mb;
    void * buffer = mb.allocate(BUFFERSIZE);

    offset_t offset = 0;
    try
    {
        loop {
            size32_t got = cmpio.get()?cmpio->read(offset, BUFFERSIZE, buffer):srcio->read(offset, BUFFERSIZE, buffer);
            if (got == 0)
                break;
            if (flzstrmdst)
                flzstrmdst->write(got,buffer);
            else
                dstio->write(offset, got, buffer);
            offset += got;
        }
    }
    catch (IException *e)
    {
        // try to delete partial copy
        dstio.clear();
        try {
            dstfile->remove();
        }
        catch (IException *e2) {
            StringBuffer s;
            pexception(s.clear().append("Removing partial copy file: ").append(to).str(),e2);
            e2->Release();
        }
        throw e;
    }
    flzstrmdst.clear();
    dstio.clear();
    if (stats) 
        printStats(offset,start,startu);
    CDateTime createTime, modifiedTime;
    if (srcfile->getTime(&createTime, &modifiedTime, NULL))
        dstfile->setTime(&createTime, &modifiedTime, NULL);
    printf("copied %s to %s%s\n",from,to,plaincopy?"":" compressing");
    { // print details 
        dstio.setown(dstfile->open(IFOread));
        if (dstio) {
            Owned<ICompressedFileIO> cmpio = createCompressedFileReader(dstio);
            Owned<IFileIOStream>  flzstrm = cmpio?NULL:createFastLZStreamRead(dstio);
            if (cmpio||flzstrm) 
                printCompDetails(to,dstio,cmpio,flzstrm);
            else 
                printf("destination %s not compressed\n",to);
        }
        else
            printf("destination %s could not be read\n",to);
    }
}