// 
// Stop profiling
// 	 
//		Input
//			Measured_Time_NS: 	Pointer to where to store the execution time
//
// 		Return: 
// 			The stop command execution status (one of enum libprf_ret_status{})
//
int
STOP_PROFILING( uint64_t *Measured_Time_NS ){
	// First get the stop cmd timestamp
	int err = (clock_gettime(CLOCK_REALTIME,&t_stop) < 0);
	if( err ){
		perror( "libprf STOP_PROFILING clock_gettime()" ); 
	}
	int status = LIBPRF_SUCCESS;
	FILE *prf_proc_file 		= NULL;
	unsigned char tx_buf[ OS_CTRL_STOP_CMD_LENGTH ];
	unsigned char rx_buf[ OS_CTRL_RX_LENGTH ];
	// Set pointer to pid field in tx buffer
	pid_t *p_id 				= (pid_t *)(&tx_buf[ OS_CTRL_TX_PID_OFFSET ]);
	*p_id				 		= getpid(); 								// PID to profile
	// Set cmd
	tx_buf[ OS_CTRL_TX_CMD_OFFSET ]	= OS_CTRL_TASK_CMD_ENABLE_OS;			// Stop cmd = OS_CTRL_TASK_CMD_ENABLE_OS				
	// Set pointer to L1 inv. time field in rx buffer
	uint64_t *pL1inv_dt 		= (uint64_t *)(&rx_buf[ OS_CTRL_RX_L1_INV_OFFSET ]);
	// Set pointer to the number of volontary context swithes between start and stop field in rx buffer
	unsigned char *pNvcsw		= &rx_buf[ OS_CTRL_RX_NVCSW_OFFSET ]; 		// Number of volontary constext switches
	// Set pointer to the number of involontary context swithes between start and stop field in rx buffer
	unsigned char *pNivcsw		= &rx_buf[ OS_CTRL_RX_NIVCSW_OFFSET ]; 		// Number of involontary constext switches
	// Reset measured time
	*Measured_Time_NS 	= 0; 
	// Open proc file in read and write mode
	if( !(prf_proc_file=fopen("/proc/os_ctrl","w+")) ){
		perror( "libprf STOP_PROFILING fopen()" ); 
		status = LIBPRF_ERR_OPEN_FILE;
	}
	// Resize buffer
	else if( setvbuf(prf_proc_file,(char *)tx_buf,_IOFBF,sizeof(tx_buf)) != 0 ){
		perror( "libprf STOP_PROFILING setvbuf()" ); 
		status = LIBPRF_ERR_BUF_RESIZE;
	}
	// Write data to os_ctrl proc file
	else if( fwrite(tx_buf,sizeof(unsigned char),sizeof(tx_buf),prf_proc_file) != sizeof(tx_buf) ){
		perror( "libprf STOP_PROFILING fwrite()" ); 
		status = LIBPRF_ERR_WRITE;
	}
	// Make sure the buffer is flushed and sent to kernel module
	else if( fflush(prf_proc_file) == EOF ){
		perror( "libprf STOP_PROFILING fflush()" ); 
		status = LIBPRF_ERR_BUF_FLUSH;
	}
	// Read answer and update *Measured_Time_NS if no error occurres
	if( fread(rx_buf,sizeof(unsigned char),sizeof(rx_buf),prf_proc_file) != sizeof(rx_buf) ) {
		perror( "libprf STOP_PROFILING fread()" ); 
		status = LIBPRF_ERR_READ;
	}
	// Close proc file
	else if( fclose(prf_proc_file) == EOF ){
		perror( "libprf START_PROFILING fclose()" ); 
		status = LIBPRF_ERR_CLOSE_FILE;
	}
	// Compute the execution time
	*Measured_Time_NS = (ELAPSED(t_start,t_stop) > *pL1inv_dt) ? (ELAPSED(t_start,t_stop) - *pL1inv_dt) : 0;
	// Return stop cmd status
	return ((status == LIBPRF_SUCCESS) && ((*Measured_Time_NS == 0) || (*pNvcsw != 0) || (*pNivcsw != 0))) ? LIBPRF_ERR_KM_BAD_VALUE : status;
}			
Example #2
0
void controllerfan_update() {
  static millis_t lastMotorOn = 0, // Last time a motor was turned on
                  nextMotorCheck = 0; // Last time the state was checked
  const millis_t ms = millis();
  if (ELAPSED(ms, nextMotorCheck)) {
    nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s

    // If any of the drivers or the bed are enabled...
    if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON
      #if HAS_HEATED_BED
        || thermalManager.soft_pwm_amount_bed > 0
      #endif
        #if HAS_X2_ENABLE
          || X2_ENABLE_READ == X_ENABLE_ON
        #endif
        #if HAS_Y2_ENABLE
          || Y2_ENABLE_READ == Y_ENABLE_ON
        #endif
        #if HAS_Z2_ENABLE
          || Z2_ENABLE_READ == Z_ENABLE_ON
        #endif
        #if HAS_Z3_ENABLE
          || Z3_ENABLE_READ == Z_ENABLE_ON
        #endif
        || E0_ENABLE_READ == E_ENABLE_ON
        #if E_STEPPERS > 1
          || E1_ENABLE_READ == E_ENABLE_ON
          #if E_STEPPERS > 2
            || E2_ENABLE_READ == E_ENABLE_ON
            #if E_STEPPERS > 3
              || E3_ENABLE_READ == E_ENABLE_ON
              #if E_STEPPERS > 4
                || E4_ENABLE_READ == E_ENABLE_ON
                #if E_STEPPERS > 5
                  || E5_ENABLE_READ == E_ENABLE_ON
                #endif
              #endif
            #endif
          #endif
        #endif
    ) {
      lastMotorOn = ms; //... set time to NOW so the fan will turn on
    }

    // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
    uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
    controllerfan_speed = speed;

    // allows digital or PWM fan output to be used (see M42 handling)
    WRITE(CONTROLLER_FAN_PIN, speed);
    analogWrite(CONTROLLER_FAN_PIN, speed);
  }
}
Example #3
0
long double
stopwatch_elapsed (const struct stopwatch_t* T)
{
    long double dt = 0;
    if (T) {
        if (IS_RUNNING (*T)) {
            DECL_RAW (stop);
            STAMP_RAW (stop);
            dt = ELAPSED (READ_START (*T), stop);
        } else {
            dt = ELAPSED (READ_START (*T), READ_STOP (*T));
        }
    }
    return dt;
}
Example #4
0
static void
unlocked_wait(void)
{
	semid_t id;
	u_int elapsed;

	if (ksem_init(&id, 1) < 0) {
		fail_errno("ksem_init");
		return;
	}

	/* This should succeed right away and set the value to 0. */
	if (testwait(id, &elapsed) < 0) {
		ksem_destroy(id);
		return;
	}
	if (!ELAPSED(elapsed, 0)) {
		fail_err("ksem_wait() of unlocked sem took %ums", elapsed);
		ksem_destroy(id);
		return;
	}
	if (checkvalue(id, 0) < 0) {
		ksem_destroy(id);
		return;
	}

	if (ksem_destroy(id) < 0) {
		fail_errno("ksem_destroy");
		return;
	}
	pass();
}
Example #5
0
static void
expired_timedwait(void)
{
	semid_t id;
	u_int elapsed;

	if (ksem_init(&id, 0) < 0) {
		fail_errno("ksem_init");
		return;
	}

	/* This should fail with a timeout and leave the value at 0. */
	if (timedwait(id, 2500, &elapsed, ETIMEDOUT) < 0) {
		ksem_destroy(id);
		return;
	}
	if (!ELAPSED(elapsed, 2500)) {
		fail_err(
	    "ksem_timedwait() of locked sem took %ums instead of 2500ms",
		    elapsed);
		ksem_destroy(id);
		return;
	}
	if (checkvalue(id, 0) < 0) {
		ksem_destroy(id);
		return;
	}

	if (ksem_destroy(id) < 0) {
		fail_errno("ksem_destroy");
		return;
	}
	pass();
}
Example #6
0
void CardReader::checkautostart(bool force) {
  if (!force && (!autostart_stilltocheck || ELAPSED(millis(), next_autostart_ms)))
    return;

  autostart_stilltocheck = false;

  if (!cardOK) {
    initsd();
    if (!cardOK) return; // fail
  }

  char autoname[10];
  sprintf_P(autoname, PSTR("auto%i.g"), autostart_index);
  for (int8_t i = 0; i < (int8_t)strlen(autoname); i++) autoname[i] = tolower(autoname[i]);

  dir_t p;

  root.rewind();

  bool found = false;
  while (root.readDir(p, NULL) > 0) {
    for (int8_t i = 0; i < (int8_t)strlen((char*)p.name); i++) p.name[i] = tolower(p.name[i]);
    if (p.name[9] != '~' && strncmp((char*)p.name, autoname, 5) == 0) {
      openAndPrintFile(autoname);
      found = true;
    }
  }
  if (!found)
    autostart_index = -1;
  else
    autostart_index++;
}
static Bool
try_get_reply (Display           *xdisplay,
               AgGetPropertyTask *task)
{
  if (ag_task_have_reply (task))
    {
      int result;
      Atom actual_type;
      int actual_format;
      unsigned long n_items;
      unsigned long bytes_after;
      unsigned char *data;
      char *name;
      struct timeval current_time;

      gettimeofday (&current_time, NULL);
      
      printf (" %gms (we have a reply for property %ld)\n",
              ELAPSED (program_start_time, current_time),
              ag_task_get_property (task));
      
      data = NULL;

      name = atom_name (xdisplay,
                        ag_task_get_property (task));
      printf (" %s on 0x%lx:\n", name,
              ag_task_get_window (task));
      free (name);
      
      result = ag_task_get_reply_and_free (task,
                                           &actual_type,
                                           &actual_format,
                                           &n_items,
                                           &bytes_after,
                                           &data);
      task = NULL;

      if (result != Success)
        {
          fprintf (stderr, "  error code %d getting reply\n", result);
        }
      else
        {
          name = atom_name (xdisplay, actual_type);
          printf ("  actual_type = %s\n", name);
          free (name);
          
          printf ("  actual_format = %d\n", actual_format);
          
          printf ("  n_items = %lu\n", n_items);
          printf ("  bytes_after = %lu\n", bytes_after);
          
          printf ("  data = \"%s\"\n", data ? (char*) data : "NULL");
        }

      return True;
    }

  return False;
}
Example #8
0
static void
locked_timedwait(void)
{
	semid_t id;
	u_int elapsed;

	if (ksem_init(&id, 0) < 0) {
		fail_errno("ksem_init");
		return;
	}

	/*
	 * Schedule a post to trigger after 1000 ms.  The subsequent
	 * timedwait should succeed after 1000 ms as a result w/o
	 * timing out.
	 */
	if (schedule_post(id, 1000) < 0) {
		ksem_destroy(id);
		return;
	}
	if (timedwait(id, 2000, &elapsed, 0) < 0) {
		check_alarm(1);
		ksem_destroy(id);
		return;
	}
	if (!ELAPSED(elapsed, 1000)) {
		fail_err(
	    "ksem_timedwait() with delayed post took %ums instead of 1000ms",
		    elapsed);
		check_alarm(1);
		ksem_destroy(id);
		return;
	}
	if (check_alarm(0) < 0) {
		ksem_destroy(id);
		return;
	}

	if (ksem_destroy(id) < 0) {
		fail_errno("ksem_destroy");
		return;
	}
	pass();
}
Example #9
0
File: P3.c Project: Solln/CS210
int main( int argc, char *argv[] ) {
    int nQs,nAs,verbose;
    
    printf(VERSION);
    /* The following (compile time) calculations of the number of questions
     * (nQs) and the number of possible answers (nAs) allows the program to
     * adjust itself automatically to the size of the data set.
     * Note: the -1 allows for the fact that as a defensive measure the 0th
     * array elements aren't counted thus allowing the indices into arrays to
     * be in the range 1 to nQs and 1 to nAs respectively. I.e. we consider
     * the arrays to have a lower bound of 1 rather than a lower bound of 0.
     * I.e. this give a more intuitive mapping of the question answers, for
     * example, where A -> 1, B -> 2, etc.
     */
    nQs = (int)(sizeof(questions)/sizeof(questions[0]))-1;
    nAs = (int)(sizeof(questions[0].pAnswers)/sizeof(questions[0].pAnswers[0]))-1;
    
#if DEBUG
    printf("Number of questions is: %d\n",nQs);
    printf("Number of answers is: %d\n",nAs);
#endif
    
    printf("%s",questions[0].pQuestion); /* 0th 'question' is the preamble */
    GetAnswer("Y");   /* Wait for a response - any, in fact, will do! */
    printf("\nThere are %d questions in this test. Good luck!\n\n",nQs);
    
    Countdown(3);     /* Output some typical Brain Trainer eye candy! */
    puts("");
    
    questions[0].aTime = SNAP(); /* Record the start time of the test */
    AskQuestions(questions,nQs,nAs); /* Self-explanatory I trust! */
    SHOT();                        /* Record the end time of the test */
    
    printf("\nThanks for taking Darren's LLP Brain Trainer Test!\n"
           "You completed the test in %d seconds\n",(int)ELAPSED());
    printf("Would you like the verbose version of your results? [Y/N]: ");
    verbose = (GetAnswer("NY") == 1);   /* Wait for a response */
    MarkAnswers(questions,nQs,options,verbose); /* Report the test results */
    
    return(0);
}
Example #10
0
void tmc2130_checkOverTemp(void) {
  static millis_t next_cOT = 0;
  if (ELAPSED(millis(), next_cOT)) {
    next_cOT = millis() + 5000;
    #if ENABLED(X_IS_TMC2130)
      automatic_current_control(stepperX, "X");
    #endif
    #if ENABLED(Y_IS_TMC2130)
      automatic_current_control(stepperY, "Y");
    #endif
    #if ENABLED(Z_IS_TMC2130)
      automatic_current_control(stepperZ, "Z");
    #endif
    #if ENABLED(X2_IS_TMC2130)
      automatic_current_control(stepperX2, "X2");
    #endif
    #if ENABLED(Y2_IS_TMC2130)
      automatic_current_control(stepperY2, "Y2");
    #endif
    #if ENABLED(Z2_IS_TMC2130)
      automatic_current_control(stepperZ2, "Z2");
    #endif
    #if ENABLED(E0_IS_TMC2130)
      automatic_current_control(stepperE0, "E0");
    #endif
    #if ENABLED(E1_IS_TMC2130)
      automatic_current_control(stepperE1, "E1");
    #endif
    #if ENABLED(E2_IS_TMC2130)
      automatic_current_control(stepperE2, "E2");
    #endif
    #if ENABLED(E3_IS_TMC2130)
      automatic_current_control(stepperE3, "E3");
    #endif
    #if ENABLED(E4_IS_TMC2130)
      automatic_current_control(stepperE4, "E4");
    #endif
  }
}
Example #11
0
/*
 * 	abcdefghijklmnopqrstuvwxyz
 *      e  hi klmno q  t u
 *      |  || ||||| |  | |
 *      |  || ||||| |  | +get screen (full res)
 *      |  || ||||| |  + touch(down,x,y)
 *      |  || ||||| +quit client
 *      |  || ||||+ftp_err
 *      |  || |||+ftp_data
 *      |  || ||+ftp_upload_req
 *      |  || |+ftp_download_req
 *      |  || +ftp_filelist_req
 *      |  |+get screen info
 *      |  +get screen (half req)
 *      +stop service
 */
static int ProcessClientMessage(svcInfoPtr psvc, FBCCMD* pmsg)
{
	//FBCCMD msg;
    //char msg;
    int n = 0;
    int nSize;

    //if( (n = ReadExact(psvc, (char*)&msg, FBCCMD_HEADER)) <= 0 ) {
    //    Err("ProcessClientMessage : read(%d)\n", n);
    //    return false;
    //}
    pmsg->size = ntohl(pmsg->size);
    pmsg->size -= FBCCMD_HEADER;
    //Log("msg received(%c: size - %d)\n", pmsg->cmd, pmsg->size);
    if( pmsg->size > 0) {
    	pmsg->data = (char*)malloc(pmsg->size);
        if( (n = ReadExact(psvc, (char*)pmsg->data, pmsg->size)) <= 0 ) {
            Err("ProcessClientMessage : read(%d)\n", n);
            return false;
        }
    }
    //Log("after alloc %02x %02x %02x %02x\n", msg.data[0],msg.data[1],msg.data[2],msg.data[3]);


    unsigned int data;
#ifdef PERFORMANCE_REPORT
	struct timeval tS, tE;

	gettimeofday(&tS,NULL);
	psvc->frame_client += ELAPSED(tLast, tS);
#endif
    switch(pmsg->cmd) {

        case 'i':
        {
        	FBCCMD_SCRINFO res;
        	res.cmd = 'i';
        	res.size = htonl(sizeof(FBCCMD_SCRINFO));

        	res.width = htonl(g_fbinfo.width);
        	res.height = htonl(g_fbinfo.height);
        	res.bpp = htonl(g_fbinfo.bpp);
        	res.touchfd = htonl( (touchfd != -1 ) ? 1 : 0);
        	LOCK(psvc->output_mutex);
            int rtn = WriteExact(psvc, (const char*)&res, sizeof(FBCCMD_SCRINFO));
            UNLOCK(psvc->output_mutex);
            //Log("response i %d to :%d\n", res.size, rtn);
        }
            break;
        case 'u':
        	//Log("signal-u\n");
        	g_halfmode = 0;
        	//TSIGNAL(psvc->updateCond);
        	read_rgb_framebuffer_to_jpeg(psvc);
#ifdef PERFORMANCE_REPORT
	gettimeofday(&tE,NULL);

	psvc->frame_total += ELAPSED(tS, tE);
	tS = tE;
#endif
            break;
        case 'h':
        	g_halfmode = 1;
        	//Log("signal-h\n");
        	//TSIGNAL(psvc->updateCond);
            //g_halfmode = 0;
            read_rgb_framebuffer_to_jpeg(psvc);
#ifdef PERFORMANCE_REPORT
	gettimeofday(&tE,NULL);

	psvc->frame_total += ELAPSED(tS, tE);
	tS = tE;
#endif
            break;
        case 'e':
            return false;
            break;
        case 'q':
        	ExitClient(psvc);
        	ShutdownSockets(psvc);
        	break;
        // ftp
        case 'k':	// ftp filestlist req
        	onFilelistReq(psvc, pmsg);
        	break;
        case 'l':	// ftp filedownload req
        	onFileDownloadReq(psvc, pmsg);
        	break;
        case 'm':	// ftp fileupload req
        	onFileUploadReq(psvc, pmsg);
        	break;
        case 'n':	// ftp fileupload data
            //Log("case n\n");

        	onFileMsg(psvc, pmsg);
        	break;
        case 'o':	// ftp fileerr
        	onFileErr(psvc, pmsg);
        	break;
        case 't':
        	onTouch(psvc, pmsg);
        	break;
    }

    if( pmsg->size > 0) {
    	free(pmsg->data);
    }

    //if(( psvc->frame_sent++ % 5) == 0) {
    //	g_fbinfo.orientation = get_dev_rotation();
    //	//int isScreenOn = get_screen_on();
    //	//Log("isScreenOn(%d)\n",isScreenOn);
    //}

#ifdef PERFORMANCE_REPORT

            if( (psvc->frame_sent % 10) == 0)
            {
            	double frame_total;
            	double frame_capture;
            	double frame_compress;
            	double frame_colorspace;
            	double frame_tx;
            	double frame_client;
            	double fps, fps_svr;



            	fps = (double)10 * 1000000 / (psvc->frame_total + psvc->frame_client);
            	fps_svr = (double)10 * 1000000 / psvc->frame_total;
            	frame_total = psvc->frame_total / 10000;
            	frame_capture = psvc->frame_capture / 10000;
            	frame_compress = psvc->frame_compress / 10000;
            	frame_colorspace = psvc->frame_colorspace / 10000;
            	frame_tx = psvc->frame_tx / 10000;
            	frame_client = psvc->frame_client / 10000;

                if( psvc->frame_sent > 10 )
                {
                	Log("FPS(%5.2f),SVR(%4.1f) TOT(%3.0f),CAP(%3.0f),ZIP(%3.0f),CNV(%2.0f),TX(%2.0f),CLI(%2.0f)\n",
                			//psvc->frame_sent-1,
                			fps, fps_svr,
                			frame_total, frame_capture, frame_compress, frame_colorspace, frame_tx,frame_client);
                }
            	psvc->frame_total		=	0;
            	psvc->frame_capture		=	0;
            	psvc->frame_compress	=	0;
            	psvc->frame_colorspace	=	0;
            	psvc->frame_tx			=	0;
            	psvc->frame_client		= 	0;

            }
            gettimeofday(&tLast,NULL);
#endif /* PERFORMANCE_REPORT */
           // Log("end loop");
    return true;

}
int main()
{
  DECL_TIMER(T0);
  DECL_TIMER(T1);


  int info = 0;
  int r = -1;

  FILE* file = fopen("./data/ACinputs.dat", "r");
  unsigned int dim = 0;
  double* reactions;
  double* velocities;
  double *mus;
  double *rhos;

  r = fscanf(file, "%d\n", &dim);
  assert(r > 0);
  if (r <= 0) return(r);

  reactions = (double *) malloc(3 * dim * sizeof(double));
  velocities = (double *) malloc(3 * dim * sizeof(double));
  mus = (double *) malloc(dim * sizeof(double));
  rhos = (double *) malloc(3 * dim * sizeof(double));

  for (unsigned int i = 0; i < dim * 3 ; ++i)
  {
    r = fscanf(file, "%lf\n", &reactions[i]);
    assert(r > 0);
  };

  for (unsigned int i = 0; i < dim * 3 ; ++i)
  {
    r = fscanf(file, "%lf\n", &velocities[i]);
    assert(r > 0);
  };

  for (unsigned int k = 0; k < dim ; ++k)
  {
    r = fscanf(file, "%lf\n", &mus[k]);
    assert(r > 0);
  };

  for (unsigned int i = 0; i < dim * 3 ; ++i)
  {
    r = fscanf(file, "%lf\n", &rhos[i]);
    assert(r > 0);
  };

  double F1[3], A1[9], B1[9],
         F2[3], A2[9], B2[9];
  for (unsigned int k = 0; k < dim; ++k)
  {

    double* p;

    p = F1;
    OP3(*p++ = NAN);

    p = F2;
    OP3(*p++ = NAN);

    p = A1;
    OP3X3(*p++ = NAN);

    p = B1;
    OP3X3(*p++ = NAN);

    p = B2;
    OP3X3(*p++ = NAN);

    p = A2;
    OP3X3(*p++ = NAN);

    START_TIMER(T0);
    DO(computeAlartCurnierSTDOld(&reactions[k * 3], &velocities[k * 3], mus[k], &rhos[k * 3], F1, A1, B1));
    STOP_TIMER(T0);

    START_TIMER(T1);
    DO(computeAlartCurnierSTD(&reactions[k * 3], &velocities[k * 3], mus[k], &rhos[k * 3], F1, A1, B1));
    STOP_TIMER(T1);

    PRINT_ELAPSED(T0);

    PRINT_ELAPSED(T1);

#ifdef WITH_TIMERS
    printf("T1/T0 = %g\n", ELAPSED(T1) / ELAPSED(T0));
#endif

    p = F1;
    OP3(info |= isnan(*p++));
    assert(!info);

    p = A1;
    OP3X3(info |= isnan(*p++));
    assert(!info);

    p = B1;
    OP3X3(info |= isnan(*p++));
    assert(!info);

    frictionContact3D_AlartCurnierFunctionGenerated(&reactions[k * 3], &velocities[k * 3], mus[k], &rhos[k * 3], F2, A2, B2);

    p = F1;
    OP3(info |= isnan(*p++));
    assert(!info);

    p = A1;
    OP3X3(info |= isnan(*p++));
    assert(!info);

    p = B1;
    OP3X3(info |= isnan(*p++));
    assert(!info);

    sub3(F1, F2);
    sub3x3(A1, A2);
    sub3x3(B1, B2);

#define EPS 1e-6
    p = F2;
    OP3(info |= !(*p++ < EPS));
    assert(!info);

    p = A2;
    OP3X3(info |= !(*p++ < EPS));
    assert(!info);

    p = B2;
    OP3X3(info |= !(*p++ < EPS));
    assert(!info);

  }

  free(reactions);
  free(velocities);
  free(mus);
  free(rhos);

  fclose(file);
  return (info);
}
/* This function doesn't have all the printf's
 * and other noise, it just compares async to sync
 */
static void
run_speed_comparison (Display *xdisplay,
                      Window   window)
{
  int i;
  int n_props;
  struct timeval start, end;
  int n_left;
  
  /* We just use atom values (0 to n_props) % 200, many are probably
   * BadAtom, that's fine, but the %200 keeps most of them valid. The
   * async case is about twice as advantageous when using valid atoms
   * (or the issue may be that it's more advantageous when the
   * properties are present and data is transmitted).
   */
  n_props = 4000;
  printf ("Timing with %d property requests\n", n_props);
  
  gettimeofday (&start, NULL);
  
  i = 0;
  while (i < n_props)
    {
      if (ag_task_create (xdisplay,
                          window, (Atom) i % 200,
                          0, 0xffffffff,
                          False,
                          AnyPropertyType) == NULL)
        {
          fprintf (stderr, "Failed to send request\n");
          exit (1);
        }
      
      ++i;
    }

  n_left = n_props;
  
  while (TRUE)
    {
      int connection;
      fd_set set;
      XEvent xevent;
      AgGetPropertyTask *task;
      
      /* Mop up event queue */
      while (XPending (xdisplay) > 0)
        XNextEvent (xdisplay, &xevent);
      
      while ((task = ag_get_next_completed_task (xdisplay)))
        {
          int UNUSED_VARIABLE result;
          Atom actual_type;
          int actual_format;
          unsigned long n_items;
          unsigned long bytes_after;
          unsigned char *data;

          assert (ag_task_have_reply (task));
          
          data = NULL;
          result = ag_task_get_reply_and_free (task,
                                               &actual_type,
                                               &actual_format,
                                               &n_items,
                                               &bytes_after,
                                               &data);
          
          if (data)
            XFree (data);
          
          n_left -= 1;
        }
      
      if (n_left == 0)
        break;

      /* Wake up if we may have a reply */
      connection = ConnectionNumber (xdisplay);

      FD_ZERO (&set);
      FD_SET (connection, &set);

      select (connection + 1, &set, NULL, NULL, NULL);
    }
  
  gettimeofday (&end, NULL);
  
  printf ("Async time: %gms\n",
          ELAPSED (start, end));
  
  gettimeofday (&start, NULL);

  error_trap_push (xdisplay);
  
  i = 0;
  while (i < n_props)
    {
      Atom actual_type;
      int actual_format;
      unsigned long n_items;
      unsigned long bytes_after;
      unsigned char *data;
      
      data = NULL;
      if (XGetWindowProperty (xdisplay, window,
                              (Atom) i % 200,
                              0, 0xffffffff,
                              False,
                              AnyPropertyType,
                              &actual_type,
                              &actual_format,
                              &n_items,
                              &bytes_after,
                              &data) == Success)
        {
          if (data)
            XFree (data);
        }
      
      ++i;
    }

  error_trap_pop (xdisplay);
  
  gettimeofday (&end, NULL);
  
  printf ("Sync time:  %gms\n",
          ELAPSED (start, end));
}
int
main (int argc, char **argv)
{
  Display *xdisplay;
  int i;
  int n_left;
  int n_props;
  Window window;
  const char *window_str;
  char *end;
  Atom *props;
  struct timeval current_time;
  
  if (argc < 2)
    {
      fprintf (stderr, "specify window ID\n");
      return 1;
    }
  
  window_str = argv[1];

  end = NULL;
  window = strtoul (window_str, &end, 0);
  if (end == NULL || *end != '\0')
    {
      fprintf (stderr, "\"%s\" does not parse as a window ID\n", window_str);
      return 1;
    }

  xdisplay = XOpenDisplay (NULL);
  if (xdisplay == NULL)
    {
      fprintf (stderr, "Could not open display\n");
      return 1;
    }

  if (getenv ("MARCO_SYNC") != NULL)
    XSynchronize (xdisplay, True);

  XSetErrorHandler (x_error_handler);
  
  n_props = 0;
  props = XListProperties (xdisplay, window, &n_props);
  if (n_props == 0 || props == NULL)
    {
      fprintf (stderr, "Window has no properties\n");
      return 1;
    }

  gettimeofday (&program_start_time, NULL);
  
  i = 0;
  while (i < n_props)
    {
      gettimeofday (&current_time, NULL);
      printf (" %gms (sending request for property %ld)\n",
              ELAPSED (program_start_time, current_time),
              props[i]);
      if (ag_task_create (xdisplay,
                          window, props[i],
                          0, 0xffffffff,
                          False,
                          AnyPropertyType) == NULL)
        {
          fprintf (stderr, "Failed to send request\n");
          return 1;
        }
      
      ++i;
    }

  XFree (props);
  props = NULL;

  n_left = n_props;
  
  while (TRUE)
    {
      XEvent xevent;
      int connection;
      fd_set set;
      AgGetPropertyTask *task;
      
      /* Mop up event queue */
      while (XPending (xdisplay) > 0)
        {                  
          XNextEvent (xdisplay, &xevent);
          gettimeofday (&current_time, NULL);
          printf (" %gms (processing event type %d)\n",
                  ELAPSED (program_start_time, current_time),
                  xevent.xany.type);
        }
      
      while ((task = ag_get_next_completed_task (xdisplay)))
        {
          try_get_reply (xdisplay, task);
          n_left -= 1;
        }

      if (n_left == 0)
        {
          printf ("All %d replies received.\n", n_props);
          break;
        }

      /* Wake up if we may have a reply */
      connection = ConnectionNumber (xdisplay);

      FD_ZERO (&set);
      FD_SET (connection, &set);

      gettimeofday (&current_time, NULL);
      printf (" %gms (blocking for data %d left)\n",
              ELAPSED (program_start_time, current_time), n_left);
      select (connection + 1, &set, NULL, NULL, NULL);
    }

  run_speed_comparison (xdisplay, window);
  
  return 0;
}
/**
 * Save the current machine state to the power-loss recovery file
 */
void PrintJobRecovery::save(const bool force/*=false*/, const bool save_queue/*=true*/) {

  #if SAVE_INFO_INTERVAL_MS > 0
    static millis_t next_save_ms; // = 0
    millis_t ms = millis();
  #endif

  if (force
    #if DISABLED(SAVE_EACH_CMD_MODE)      // Always save state when enabled
      #if PIN_EXISTS(POWER_LOSS)          // Save if power loss pin is triggered
        || READ(POWER_LOSS_PIN) == POWER_LOSS_STATE
      #endif
      #if SAVE_INFO_INTERVAL_MS > 0       // Save if interval is elapsed
        || ELAPSED(ms, next_save_ms)
      #endif
      // Save every time Z is higher than the last call
      || current_position[Z_AXIS] > info.current_position[Z_AXIS]
    #endif
  ) {

    #if SAVE_INFO_INTERVAL_MS > 0
      next_save_ms = ms + SAVE_INFO_INTERVAL_MS;
    #endif

    // Set Head and Foot to matching non-zero values
    if (!++info.valid_head) ++info.valid_head; // non-zero in sequence
    //if (!IS_SD_PRINTING()) info.valid_head = 0;
    info.valid_foot = info.valid_head;

    // Machine state
    COPY(info.current_position, current_position);
    info.feedrate = uint16_t(feedrate_mm_s * 60.0f);

    #if HOTENDS > 1
      info.active_hotend = active_extruder;
    #endif

    HOTEND_LOOP() info.target_temperature[e] = thermalManager.temp_hotend[e].target;

    #if HAS_HEATED_BED
      info.target_temperature_bed = thermalManager.temp_bed.target;
    #endif

    #if FAN_COUNT
      COPY(info.fan_speed, thermalManager.fan_speed);
    #endif

    #if HAS_LEVELING
      info.leveling = planner.leveling_active;
      info.fade = (
        #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
          planner.z_fade_height
        #else
          0
        #endif
      );
    #endif

    #if ENABLED(GRADIENT_MIX)
      memcpy(&info.gradient, &mixer.gradient, sizeof(info.gradient));
    #endif

    #if ENABLED(FWRETRACT)
      COPY(info.retract, fwretract.current_retract);
      info.retract_hop = fwretract.current_hop;
    #endif

    // Commands in the queue
    info.commands_in_queue = save_queue ? commands_in_queue : 0;
    info.cmd_queue_index_r = cmd_queue_index_r;
    COPY(info.command_queue, command_queue);

    // Elapsed print job time
    info.print_job_elapsed = print_job_timer.duration();

    // SD file position
    card.getAbsFilename(info.sd_filename);
    info.sdpos = card.getIndex();

    write();

    // KILL now if the power-loss pin was triggered
    #if PIN_EXISTS(POWER_LOSS)
      if (READ(POWER_LOSS_PIN) == POWER_LOSS_STATE) kill(PSTR(MSG_OUTAGE_RECOVERY));
    #endif
  }
}
int
main(int argc, char **argv)
{
    int nItCG, nLevel = 2;
    long TIME[9];
    int nBdry = 2;

    pcoo S = new_coo(1,1,1);
    pcrs A = new_crs(1,1,1);
    pindexmatrix edgeno = new_indexmatrix(0,0);

    pindexmatrix   *s2p = NULL;
    pindexvector   *fixedNodes = NULL;
    pindexvector material;
    prealmatrix coordinates;
    pindexmatrix elements;
    pindexmatrix elements2edges;

    pindexvector bdrytyp = new_indexvector(2);
    pindexmatrix bdrylist[2];
    pindexvector bdry2edgeslist[2];

    prealvector rhs;
    prealvector sol;

    /* Number of refinements */ 
    if (argc>1){
      if (atoi(argv[1]) < 12) nLevel = atoi(argv[1]);
    }
    /* Load geometry */
    material
            = load_indexvector("./Tests/Example1/material.dat");
    coordinates
            = load_realmatrix("./Tests/Example1/coordinates.dat",(index)2,1);
    elements
            = load_indexmatrix("./Tests/Example1/elements.dat",3,1);
    elements2edges
            = load_indexmatrix("./Tests/Example1/elements2edges.dat",3,1);
    bdrytyp->vals[0] = 0;
    bdrytyp->vals[1] = 1;
    bdrylist[0] = load_indexmatrix("./Tests/Example1/Dirichlet.dat",2,1);
    bdrylist[1] = load_indexmatrix("./Tests/Example1/Neumann.dat",2,1);
    bdry2edgeslist[0] = load_indexvector("./Tests/Example1/Dirichlet2edges.dat");
    bdry2edgeslist[1] = load_indexvector("./Tests/Example1/Neumann2edges.dat");


    /* Show geometry */
    printf("====================\n");
    printf("coordinates:\n");
    printf("====================\n");
    print_realmatrix(coordinates);
    printf("====================\n");
    printf("elements:\n");
    printf("====================\n");
    print_indexmatrix(elements);
    printf("====================\n");
    printf("elements2edges:\n");
    printf("====================\n");
    print_indexmatrix(elements2edges);
    printf("====================\n");
    printf("material:\n");
    printf("====================\n");
    print_indexvector(material);
    printf("====================\n");
    printf("bdrylist:\n");
    printf("====================\n");
    print_indexmatrix(bdrylist[0]);
    printf("--------------------\n");
    print_indexmatrix(bdrylist[1]);
    printf("====================\n");
    printf("bdry2edgeslist:\n");
    printf("====================\n");
    print_indexvector(bdry2edgeslist[0]);
    printf("--------------------\n");
    print_indexvector(bdry2edgeslist[1]);
    printf("====================\n");

    TIME[0] = clock();

    /* Refine mesh uniformly */
    create_hierarchy(nLevel,            /* in       */
                     coordinates,       /* in / out */
                     elements,          /* in / out */
                     material,          /* in / out */
                     elements2edges,    /* in       */
                     s2p,               /* out      */
                     nBdry,             /* in       */
                     bdrytyp,           /* in       */
                     bdrylist,          /* in / out */
                     bdry2edgeslist,          /* in / out */
                     NULL,              /* in / out */
                     fixedNodes);            /* in / out */

    TIME[1] = clock();

    write_realmatrix("./Tests/Example1/coordinates_fine.dat",coordinates,1);
    write_indexmatrix("./Tests/Example1/elements_fine.dat",elements,1);
    write_indexmatrix("./Tests/Example1/elements2edges_fine.dat",elements,1);
    write_indexvector("./Tests/Example1/material_fine.dat",material);
    write_indexmatrix("./Tests/Example1/Dirichlet_fine.dat",bdrylist[0],1);
    write_indexmatrix("./Tests/Example1/Neumann_fine.dat",bdrylist[1],1);
    write_indexvector("./Tests/Example1/Dirichlet2edges_fine.dat",bdry2edgeslist[0]);
    write_indexvector("./Tests/Example1/Neumann2edges_fine.dat",bdry2edgeslist[1]);

    rhs = new_realvector(coordinates->cols);
    sol = new_realvector(coordinates->cols);

    TIME[2] = clock();

    buildStiffness(coordinates, elements, S);

    TIME[3] = clock();

    init_coo2crs(A, S);

    TIME[4] = clock();

    buildRhs(coordinates, elements, VolForce, rhs);
    copy_realvector(sol, rhs);
    setDirichletData2Rhs(coordinates, fixedNodes[0], uD, sol);

    TIME[5] = clock();

    nItCG = cgcrs_constrains(A,sol,rhs, fixedNodes[0],1e-6,coordinates->cols);
    printf("No. iterations %i\n", nItCG);

    TIME[6] = clock();

    write_realvector("./Tests/Example1/sol_fine.dat",sol);

    TIME[7] = clock();

    printf("---------------------\n");
    printf("Time for refinement       = %i ms\n", ELAPSED(TIME[0],TIME[1]));
    printf("Time for saving ref. mesh = %i ms\n", ELAPSED(TIME[1],TIME[2]));
    printf("Time for assembling       = %i ms\n", ELAPSED(TIME[2],TIME[3]));
    printf("Time for COO -> CRS       = %i ms\n", ELAPSED(TIME[3],TIME[4]));
    printf("Time for RHS              = %i ms\n", ELAPSED(TIME[4],TIME[5]));
    printf("Time for solving          = %i ms\n", ELAPSED(TIME[5],TIME[6]));
    printf("Time store solution       = %i ms\n\n", ELAPSED(TIME[6],TIME[7]));
    printf("Degrees of elements / freedom %lu / %lu\n", elements->cols, coordinates->cols);

    printf("---------------------\n");

    del_coo(S);
    del_crs(A);
    del_realvector(rhs); 
    del_realvector(sol);
    del_indexmatrix(edgeno);


    del_realmatrix(coordinates);
    del_indexmatrix(elements);
    del_indexmatrix(elements2edges);
    del_indexvector(material);
 
    return 0;
}