Esempio n. 1
0
int clockwrapper() {
  return (int) times(NULL);
}
Esempio n. 2
0
void Timer::cont() {
  tms buffer;
  mRealTime = times(&buffer)/sHZ;
  mUserTime = buffer.tms_utime/sHZ;
  mSysTime = buffer.tms_stime/sHZ;
}
Esempio n. 3
0
int main() {
	
	char input[MAXSIZE];						// Input from the user
	char *args[MAXARGS];					// Array of arguments
	char *command;								// Holds the result of the strtok function
	char *redir_in;							// Holds the input redirection file
	char *redir_out;							// Holds the output redirection file
	struct tms timer_start;					// Holds the CPU start time struct
	struct tms timer_end;					// Holds the CPU end time struct
	time_t real_start;						// Stores the starting real time
	time_t real_end;							// Stores the ending real time
	int counter = 1;							// A counter next to the input line
	int status = 0;							// Stores the error status
	int num_args = 0;							// Stores the number of arguments in the current command
	char timer = 0;							// Boolean if "time" was entered first
	char read = 0;								// Boolean for input redirection
	char write = 0;							// Boolean for output redirection
	
	
	while (1) {
		printf("(%d) blueshell $ ", counter);			// "blueshell" pays homage to the notorious Mario Kart item
		
		if (!fgets(input, 1000, stdin)) {				// Exits the shell if fgets returns NULL
			return 1;
		}
		if (strlen(input) <= 1) {				// Continues the loop if an empty string is entered
			continue;
		}
		
		num_args = 0;					// Resets the associated accumulators and booleans
		timer = 0;
		read = 0;
		write = 0;
		errno = 0;
		status = 0;
		counter++;						// Increments the shell counter
		
		redir_in = strchr(input, '<');				// Searches for the input redirection character
		redir_out = strchr(input, '>');				// Searches for the output redirection character
		
		if (redir_in != NULL) {									// Stores the input file if redir_in is not null
			redir_in = strtok(redir_in, DELIMS);
			read = 1;
		}
		if (redir_out != NULL) {								// Stores the output file if redir_in is not null
			redir_out = strtok(redir_out, DELIMS);
			write = 1;
		}
		
		command = strtok(input, DELIMS);					// Delimits the first token in the input
		
		if (command == NULL) {					// Continues the loop if the token is null
			continue;
		}
		if (0 == strcmp(command, "exit")) {			// Exits the shell if the token is "exit"
			exit(0);
		}
		if (0 == strcmp(command, "time")) {			// Starts the CPU timer if the token is "time"
			command = strtok(NULL, DELIMS);			// Gets the next token (since time is not included as a command)
			timer = 1;										// Sets the time boolean to "true"
			real_start = time(NULL);					// Sets the realtime start
			times(&timer_start);							// Sets the CPU times start
		}
		
		while (command != NULL) {						// Loops while there is something to tokenize
			char valid = 1;						// Boolean validating the token
			
			if (read) {
				if (0 == strcmp(command, redir_in)) {			// Keeps the input redirection file out of the arguments
					valid = 0;
				}
			}
			if (write) {
				if (0 == strcmp(command, redir_out)) {			// Keeps the output redirection file out of the arguments
					valid = 0;
				}
			}
			
			if (valid) {
				args[num_args++] = command;			// If the argument is valid, it is added to the array and the arg_count is incremeneted
			}
			
			command = strtok(NULL, DELIMS);				// Gets the next token of the input
		}
		
		if (num_args < MAXARGS) {
			args[num_args] = NULL;					// Sets the pointer after the last argument to null
		}
		else {
			printf("-blueshell: %s: Arg list too long\n", args[0]);		// Prints an error if the maximum number of arguments have been reached
			continue;
		}
		
		if (args[0] != NULL) {							// Checks various conditions if a command has been entered
			if (0 == strcmp(args[0], "cd")) {				// Conditional if the command is "cd"
				if (num_args > 1) {								// Conditional if there are arguments for "cd"
					if ('~' == args[1][0]) {					// Conditional if the first character is a tilde
						char *path;							// Holds the Pitt Net path prefix
						char *argument;					// Stores the modified argument
						int len = 0;						// Length of the argument
						
						argument = strtok(args[1], "~");				// Tokenizes the argument of the tilde
						len = strlen(argument);						// Gets the length of the modified argument
						path = malloc(len * sizeof(char) + 24 * sizeof(char));		// Allocates memory for the full path string
						
						strcpy(path, "/afs/pitt.edu/home/");				// Builds a string of the full pathname
						strncat(path, argument, 1);
						strncat(path, "/", 1);
						strncat(path, argument + 1 * sizeof(char), 1);
						strncat(path, "/", 1);
						strcat(path, argument);
						
						status = chdir(path);					// Attempts to change the current directory
						free(path);						// Frees memory allocated for the string
					}
					else {
						status = chdir(args[1]);			// Otherwise, changes the directory to the argument specified
					}
				}
				else {							// Otherwise, changes to the default directory of the user
					char *path;					// Pointer to the pathname
					char *user;					// Pointer to the username
					int len = 0;				// Length of the full pathname
					
					user = getlogin();			// Gets the username
					len = strlen(user);			// Gets the length of the username
					
					path = malloc(len * sizeof(char) + 24 * sizeof(char));			// Allocates memory for the path
					
					strcpy(path, "/afs/pitt.edu/home/");					// Builds the default pathname
					strncat(path, user, 1);
					strncat(path, "/", 1);
					strncat(path, user + 1 * sizeof(char), 1);
					strncat(path, "/", 1);
					strcat(path, user);
					
					status = chdir(path);				// Attempts to change the current directory
					free(path);								// Frees memory allocated for the string
				}
				
				if (status < 0) {						// If chdir() returned -1, prints the errno message
					print_error(args[1]);
				}
			}
			else {								// Otherwise, attempts to fork the process and call execvp()
				int pid = fork();				// Gets the process ID
				
				if (0 == pid) {				// The child process has an ID of 0
					if (read) {									// If input redirection is true
						if (freopen(redir_in, "r", stdin) == NULL) {			// Prints an error if the file descriptor is null
							print_error(redir_in);
							_exit(-1);
						}
					}
					if (write) {								// If output redirection is true
						if (freopen(redir_out, "w", stdout) == NULL) {		// Prints an error if the file descriptor is null
							print_error(redir_out);
							_exit(-1);
						}
					}
					
					status = execvp(args[0], args);			// Attempts to run the command and associated arguments
					
					if (status < 0) {						// Prints an eror if execvp returns -1
						print_error(args[0]);
						_exit(-1);
					}
					
					_exit(0);
				}
				else if (pid < 0) {						// If the process ID is negative, prints an error
					print_error(args[0]);
					_exit(-1);
				}
				else {									// Otherwise, the process is the parent
					wait(&status);						// Waits for the child process to complete
					
					if (status < 0) {							// Prints an error if the status is -1
						print_error(args[0]);
					}
				}
			}
		}
		
		if (timer) {						// Gets the end real, user, and system times
			times(&timer_end);					// Gets the ending CPU times
			real_end = time(NULL);						// Gets the realtime end
			printf("real\t%lds\n", real_end - real_start);					// Prints the elapsed real time
			printf("user\t%jds\n", (intmax_t)(timer_end.tms_cutime - timer_start.tms_cutime));		// Prints the user CPU time
			printf("sys\t%jds\n", (intmax_t)(timer_end.tms_cstime - timer_start.tms_cstime));		// Prints the system CPU time
		}
	}
}
Esempio n. 4
0
/*
| Normal operation happens in here.
*/
static void
masterloop(lua_State *L)
{
	while( true )
	{
		bool have_alarm;
		bool force_alarm   = false;
		clock_t now        = times( dummy_tms );
		clock_t alarm_time = 0;

		// memory usage debugging
		// lua_gc( L, LUA_GCCOLLECT, 0 );
		// printf(
		//     "gccount: %d\n",
		//     lua_gc( L, LUA_GCCOUNT, 0 ) * 1024 + lua_gc( L, LUA_GCCOUNTB, 0 ) );

		//
		// queries the runner about the soonest alarm
		//
		load_runner_func( L, "getAlarm" );

		if( lua_pcall( L, 0, 1, -2 ) )
		{
			exit( -1 );
		}

		if( lua_type( L, -1 ) == LUA_TBOOLEAN)
		{
			have_alarm = false;
			force_alarm = lua_toboolean( L, -1 );
		}
		else
		{
			have_alarm = true;
			alarm_time = *( ( clock_t * ) luaL_checkudata( L, -1, "Lsyncd.jiffies" ) );
		}

		lua_pop( L, 2 );

		if(
			force_alarm ||
			( have_alarm && time_before_eq( alarm_time, now ) )
		)
		{
			// there is a delay that wants to be handled already thus instead
			// of reading/writing from observances it jumps directly to
			// handling

			// TODO: Actually it might be smarter to handler observances
			// eitherway. since event queues might overflow.
			logstring( "Masterloop", "immediately handling delays." );
		}
		else
		{
			// uses select( ) to determine what happens next:
			//   a) a new event on an observance
			//   b) an alarm on timeout
			//   c) the return of a child process
			struct timespec tv;

			if( have_alarm )
			{
				// TODO use trunc instead of long converstions
				double d   = ( (double )( alarm_time - now ) ) / clocks_per_sec;
				tv.tv_sec  = d;
				tv.tv_nsec = ( (d - ( long ) d) ) * 1000000000.0;
				printlogf(
					L, "Masterloop",
					"going into select ( timeout %f seconds )",
					d
				);
			}
			else
			{
				logstring(
					"Masterloop",
					"going into select ( no timeout )"
				);
			}

			// time for Lsyncd to try to put itself to rest into the big select( )
			// this configures:
			//    timeouts,
			//    filedescriptors and
			//    signals
			// that will wake Lsyncd
			{
				fd_set rfds;
				fd_set wfds;
				sigset_t sigset;
				int pi, pr;

				sigemptyset( &sigset );
				FD_ZERO( &rfds );
				FD_ZERO( &wfds );

				for( pi = 0; pi < observances_len; pi++ )
				{
					struct observance *obs = observances + pi;
					if ( obs->ready  )
					{
						FD_SET( obs->fd, &rfds );
					}

					if ( obs->writey )
					{
						FD_SET( obs->fd, &wfds );
					}
				}

				if( !observances_len )
				{
					logstring(
						"Error",
						"Internal fail, no observances, no monitor!"
					);

					exit( -1 );
				}

				// the great select, this is the very heart beat of Lsyncd
				// that puts Lsyncd to sleep until anything worth noticing
				// happens

				pr = pselect(
					observances[ observances_len - 1 ].fd + 1,
					&rfds,
					&wfds,
					NULL,
					have_alarm ? &tv : NULL,
					&sigset
				);

				// something happened!

				if (pr >= 0)
				{
					// walks through the observances calling ready/writey
					observance_action = true;

					for( pi = 0; pi < observances_len; pi++ )
					{
						struct observance *obs = observances + pi;

						// Checks for signals
						if( hup || term )
						{
							break;
						}

						// a file descriptor became read-ready
						if( obs->ready && FD_ISSET( obs->fd, &rfds ) )
						{
							obs->ready(L, obs);
						}

						// Checks for signals, again, better safe than sorry
						if ( hup || term )
						{
							break;
						}

						// FIXME breaks on multiple nonobservances in one beat
						if(
							nonobservances_len > 0 &&
							nonobservances[ nonobservances_len - 1 ] == obs->fd
						)
						{
							continue;
						}

						// a file descriptor became write-ready
						if( obs->writey && FD_ISSET( obs->fd, &wfds ) )
						{
							obs->writey( L, obs );
						}
					}

					observance_action = false;

					// works through delayed nonobserve_fd() calls
					for (pi = 0; pi < nonobservances_len; pi++)
					{
						nonobserve_fd( nonobservances[ pi ] );
					}

					nonobservances_len = 0;
				}
			}
		}

		// collects zombified child processes
		while( 1 )
		{
			int status;
			pid_t pid = waitpid( 0, &status, WNOHANG );

			if (pid <= 0)
			{
				// no more zombies
				break;
			}

			// calls the runner to handle the collection
			load_runner_func( L, "collectProcess" );
			lua_pushinteger( L, pid );
			lua_pushinteger( L, WEXITSTATUS( status ) );

			if ( lua_pcall( L, 2, 0, -4 ) )
				{ exit(-1); }

			lua_pop( L, 1 );
		}

		// reacts on HUP signals
		if( hup )
		{
			load_runner_func( L, "hup" );

			if( lua_pcall( L, 0, 0, -2 ) )
			{
				exit( -1 );
			}

			lua_pop( L, 1 );

			hup = 0;
		}

		// reacts on TERM and INT signals
		if( term == 1 )
		{
			load_runner_func( L, "term" );

			lua_pushnumber( L, sigcode );

			if( lua_pcall( L, 1, 0, -3 ) )
			{
				exit( -1 );
			}

			lua_pop( L, 1 );

			term = 2;
		}

		// lets the runner do stuff every cycle,
		// like starting new processes, writing the statusfile etc.
		load_runner_func( L, "cycle" );

		l_now( L );

		if( lua_pcall( L, 1, 1, -3 ) )
		{
			exit( -1 );
		}

		if( !lua_toboolean( L, -1 ) )
		{
			// cycle told core to break mainloop
			lua_pop( L, 2 );
			return;
		}
		lua_pop( L, 2 );

		if( lua_gettop( L ) )
		{
			logstring(
				"Error",
				"internal, stack is dirty."
			);
			l_stackdump( L );
			exit( -1 );
		}
	}
}
Esempio n. 5
0
File: 8-1.c Progetto: Nan619/ltp-ddt
int main(int argc, char *argv[])
{
    struct tms ini_tms, parent_tms, child_tms;

    int status;
    pid_t child, ctl;

    clock_t st_time, cur_time;

    output_init();

    st_time = times(&ini_tms);

    if (st_time == -1)
        UNRESOLVED(errno, "times failed");

    if (ini_tms.tms_cutime != 0 || ini_tms.tms_cstime != 0)
        FAILED("The process is created with non-zero tms_cutime or "
               "tms_cstime");

#if VERBOSE > 1
    output("Starting loop...\n");
#endif

    /* Busy loop for some times */
    do {
        cur_time = times(&parent_tms);

        if (cur_time == (clock_t) - 1)
            UNRESOLVED(errno, "times failed");
    } while ((cur_time - st_time) < sysconf(_SC_CLK_TCK));

#if VERBOSE > 1
    output("Busy loop terminated\n");
    output
    (" Real time: %ld, User Time %ld, System Time %ld, Ticks per sec %ld\n",
     (long)(cur_time - st_time),
     (long)(parent_tms.tms_utime - ini_tms.tms_utime),
     (long)(parent_tms.tms_stime - ini_tms.tms_stime),
     sysconf(_SC_CLK_TCK));
#endif

    /* Create the child */
    child = fork();

    if (child == -1)
        UNRESOLVED(errno, "Failed to fork");

    /* child */
    if (child == 0) {

        cur_time = times(&child_tms);

        if (cur_time == (clock_t) - 1)
            UNRESOLVED(errno, "times failed");

        if ((child_tms.tms_utime + child_tms.tms_stime) >=
                sysconf(_SC_CLK_TCK))
            FAILED("The tms struct was not reset during fork "
                   "operation");

        do {
            cur_time = times(&child_tms);

            if (cur_time == -1)
                UNRESOLVED(errno, "times failed");
        } while ((child_tms.tms_utime + child_tms.tms_stime) <= 0);

        /* We're done */
        exit(PTS_PASS);
    }

    /* Parent joins the child */
    ctl = waitpid(child, &status, 0);

    if (ctl != child)
        UNRESOLVED(errno, "Waitpid returned the wrong PID");

    if (!WIFEXITED(status) || WEXITSTATUS(status) != PTS_PASS)
        FAILED("Child exited abnormally");

    /* Check the children times were reported as expected */
    cur_time = times(&parent_tms);

#if VERBOSE > 1

    output("Child joined\n");

    output(" Real time: %ld,\n"
           "  User Time %ld, System Time %ld,\n"
           "  Child User Time %ld, Child System Time %ld\n",
           (long)(cur_time - st_time),
           (long)(parent_tms.tms_utime - ini_tms.tms_utime),
           (long)(parent_tms.tms_stime - ini_tms.tms_stime),
           (long)(parent_tms.tms_cutime - ini_tms.tms_cutime),
           (long)(parent_tms.tms_cstime - ini_tms.tms_cstime)
          );

#endif

    if (cur_time == -1)
        UNRESOLVED(errno, "times failed");

    if (parent_tms.tms_cutime == 0 && parent_tms.tms_cstime == 0)
        FAILED("The process is created with non-zero tms_cutime or "
               "tms_cstime");

    /* Test passed */
#if VERBOSE > 0

    output("Test passed\n");

#endif

    PASSED;
}
Esempio n. 6
0
/*
  Returns true if the real time clock has changed by more than 10%
  relative to the processor time since the last time this function was
  called. This presumably means that the system time has been changed.

  If /a delta is nonzero, delta is set to our best guess at how much the system clock was changed.
*/
bool QTimerInfoList::timeChanged(timeval *delta)
{
#ifdef Q_OS_NACL
    Q_UNUSED(delta)
    return false; // Calling "times" crashes.
#endif
    struct tms unused;
    clock_t currentTicks = times(&unused);

    clock_t elapsedTicks = currentTicks - previousTicks;
    timeval elapsedTime = currentTime - previousTime;

    timeval elapsedTimeTicks;
    elapsedTimeTicks.tv_sec = elapsedTicks / ticksPerSecond;
    elapsedTimeTicks.tv_usec = (((elapsedTicks * 1000) / ticksPerSecond) % 1000) * 1000;

    timeval dummy;
    if (!delta)
        delta = &dummy;
    *delta = elapsedTime - elapsedTimeTicks;

    previousTicks = currentTicks;
    previousTime = currentTime;
Esempio n. 7
0
Proc0(long numloops, boolean print_result)
{
	OneToFifty		IntLoc1;
	REG OneToFifty		IntLoc2;
	OneToFifty		IntLoc3;
	REG char		CharLoc;
	REG char		CharIndex;
	Enumeration	 	EnumLoc;
	String30		String1Loc;
	String30		String2Loc;
	//	extern char		*malloc();

	register unsigned int	i;
#ifdef TIME
	long			time();
	long			starttime;
	long			benchtime;
	long			nulltime;

	starttime = time( (long *) 0);
	for (i = 0; i < numloops; ++i);
	nulltime = time( (long *) 0) - starttime; /* Computes o'head of loop */
#endif
#ifdef TIMES
	time_t			starttime;
	time_t			benchtime;
	time_t			nulltime;
	struct tms		tms;

	times(&tms); starttime = tms.tms_utime;
	for (i = 0; i < numloops; ++i);
	times(&tms);
	nulltime = tms.tms_utime - starttime; /* Computes overhead of looping */
#endif
#ifdef GETRUSAGE
	struct rusage starttime;
	struct rusage endtime;
	struct timeval nulltime;

	getrusage(RUSAGE_SELF, &starttime);
	for (i = 0; i < numloops; ++i);
	getrusage(RUSAGE_SELF, &endtime);
	nulltime.tv_sec  = endtime.ru_utime.tv_sec  - starttime.ru_utime.tv_sec;
	nulltime.tv_usec = endtime.ru_utime.tv_usec - starttime.ru_utime.tv_usec;
#endif

	PtrGlbNext = (RecordPtr) malloc(sizeof(RecordType));
	PtrGlb = (RecordPtr) malloc(sizeof(RecordType));
	PtrGlb->PtrComp = PtrGlbNext;
	PtrGlb->Discr = Ident1;
	PtrGlb->EnumComp = Ident3;
	PtrGlb->IntComp = 40;
	strcpy(PtrGlb->StringComp, "DHRYSTONE PROGRAM, SOME STRING");
#ifndef	GOOF
	strcpy(String1Loc, "DHRYSTONE PROGRAM, 1'ST STRING");	/*GOOF*/
#endif
	Array2Glob[8][7] = 10;	/* Was missing in published program */

/*****************
-- Start Timer --
*****************/
#ifdef TIME
	starttime = time( (long *) 0);
#endif
#ifdef TIMES
	times(&tms); starttime = tms.tms_utime;
#endif
#ifdef GETRUSAGE
	getrusage (RUSAGE_SELF, &starttime);
#endif
	for (i = 0; i < numloops; ++i)
	{

		Proc5();
		Proc4();
		IntLoc1 = 2;
		IntLoc2 = 3;
		strcpy(String2Loc, "DHRYSTONE PROGRAM, 2'ND STRING");
		EnumLoc = Ident2;
		BoolGlob = ! Func2(String1Loc, String2Loc);
		while (IntLoc1 < IntLoc2)
		{
			IntLoc3 = 5 * IntLoc1 - IntLoc2;
			Proc7(IntLoc1, IntLoc2, &IntLoc3);
			++IntLoc1;
		}
		Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3);
		Proc1(PtrGlb);
		for (CharIndex = 'A'; CharIndex <= Char2Glob; ++CharIndex)
			if (EnumLoc == Func1(CharIndex, 'C'))
				Proc6(Ident1, &EnumLoc);
		IntLoc3 = IntLoc2 * IntLoc1;
		IntLoc2 = IntLoc3 / IntLoc1;
		IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1;
		Proc2(&IntLoc1);
	}

/*****************
-- Stop Timer --
*****************/

	if (print_result) {
#ifdef TIME
		benchtime = time( (long *) 0) - starttime - nulltime;
		printf("Dhrystone(%s) time for %ld passes = %ld\n",
			Version,
			(long) numloops, benchtime);
		printf("This machine benchmarks at %ld dhrystones/second\n",
			((long) numloops) / benchtime);
		printf("                           %ld DMIPS\n",
			((long) numloops) / benchtime / ONE_MIPS);
#endif
#ifdef TIMES
		times(&tms);
		benchtime = tms.tms_utime - starttime - nulltime;
		printf("Dhrystone(%s) time for %ld passes = %ld\n",
			Version,
			(long) numloops, benchtime/HZ);
		printf("This machine benchmarks at %ld dhrystones/second\n",
			((long) numloops) * HZ / benchtime);
		printf("                           %ld DMIPS\n",
			((long) numloops) * HZ / benchtime / ONE_MIPS);
#endif
#ifdef GETRUSAGE
		getrusage(RUSAGE_SELF, &endtime);
		{
		    double t = (double)(endtime.ru_utime.tv_sec
					- starttime.ru_utime.tv_sec
					- nulltime.tv_sec)
			     + (double)(endtime.ru_utime.tv_usec
					- starttime.ru_utime.tv_usec
					- nulltime.tv_usec) * 1e-6;
		    printf("Dhrystone(%s) time for %ld passes = %.1f\n",
			   Version,
			   (long)numloops,
			   t);
		    printf("This machine benchmarks at %.0f dhrystones/second\n",
			   (double)numloops / t);
		    printf("                           %.0f DMIPS\n",
			   (double)numloops / t / ONE_MIPS);
		}
#endif
	}

}
Esempio n. 8
0
/*
** [ENTRY POINT] does : this is the function called by nginx : 
** - Set up the context for the request
** - Check if the job is done and we're called again
** - if it's a PATCH/POST/PUT request, setup hook for body dataz
** - call dummy_data_parse
** - check our context struct (with scores & stuff) against custom check rules
** - check if the request should be denied
*/
static ngx_int_t ngx_http_dummy_access_handler(ngx_http_request_t *r)
{
  ngx_http_request_ctx_t	*ctx;
  ngx_int_t			rc;
  ngx_http_dummy_loc_conf_t	*cf;
  struct tms		 tmsstart, tmsend;
  clock_t		 start, end;
  ngx_http_variable_value_t *lookup;


  static ngx_str_t learning_flag = ngx_string(RT_LEARNING);
  static ngx_str_t enable_flag = ngx_string(RT_ENABLE);
  static ngx_str_t post_action_flag = ngx_string(RT_POST_ACTION);
  static ngx_str_t extensive_log_flag = ngx_string(RT_EXTENSIVE_LOG);
  static ngx_str_t libinjection_sql_flag = ngx_string(RT_LIBINJECTION_SQL);
  static ngx_str_t libinjection_xss_flag = ngx_string(RT_LIBINJECTION_XSS);

  
  ctx = ngx_http_get_module_ctx(r, ngx_http_naxsi_module);
  cf = ngx_http_get_module_loc_conf(r, ngx_http_naxsi_module);
  
  if (ctx && ctx->over)
    return (NGX_DECLINED);
  if (ctx && ctx->wait_for_body) {   
    NX_DEBUG(_debug_mechanics, NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
	     "naxsi:NGX_AGAIN");
    return (NGX_DONE);
  }
  if (!cf) 
    return (NGX_ERROR);
  /* the module is not enabled here */
  /* if enable directive is not present at all in the location, 
     don't try to do dynamic lookup for "live" enabled
     naxsi, this would be very rude. */
  if (!cf->enabled)
    return (NGX_DECLINED);
  /* On the other hand, if naxsi has been explicitly disabled 
     in this location (using naxsi directive), user is probably
     trying to do something.  */
  if (cf->force_disabled) {
    /* Look if the user did not try to enable naxsi dynamically */
    lookup = ngx_http_get_variable(r, &enable_flag, cf->flag_enable_h);
    if (lookup && !lookup->not_found && lookup->len > 0) {
      ngx_log_debug(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		    "live enable is present %d", lookup->data[0] - '0');
      if (lookup->data[0] - '0' != 1) {
	return (NGX_DECLINED);}
    }
    else
      return (NGX_DECLINED);
  }
  /* don't process internal requests. */
  if (r->internal) {   
    NX_DEBUG(_debug_mechanics, NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
	     "XX-DON'T PROCESS (%V)|CTX:%p|ARGS:%V|METHOD=%s|INTERNAL:%d", &(r->uri), ctx, &(r->args),
	     r->method == NGX_HTTP_PATCH ? "PATCH" : r->method == NGX_HTTP_POST ? "POST" : r->method == NGX_HTTP_PUT ? "PUT" : r->method == NGX_HTTP_GET ? "GET" : "UNKNOWN!!",
	     r->internal);
    return (NGX_DECLINED);
  } 
  NX_DEBUG(_debug_mechanics, NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
	   "XX-processing (%V)|CTX:%p|ARGS:%V|METHOD=%s|INTERNAL:%d", &(r->uri), ctx, &(r->args),
	   r->method == NGX_HTTP_PATCH ? "PATCH" : r->method == NGX_HTTP_POST ? "POST" : r->method == NGX_HTTP_PUT ? "PUT" : r->method == NGX_HTTP_GET ? "GET" : "UNKNOWN!!",
	   r->internal);
  if (!ctx) {
    ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_request_ctx_t));
    if (ctx == NULL)
      return NGX_ERROR;
    ngx_http_set_ctx(r, ctx, ngx_http_naxsi_module);
    NX_DEBUG(_debug_modifier, NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
	     "XX-dummy : orig learning : %d", cf->learning ? 1 : 0);
    /* it seems that nginx will - in some cases - 
     have a variable with empty content but with lookup->not_found set to 0,
    so check len as well */
    ctx->learning = cf->learning;
    
    lookup = ngx_http_get_variable(r, &learning_flag, cf->flag_learning_h);
    if (lookup && !lookup->not_found && lookup->len > 0) {
      
      ctx->learning = lookup->data[0] - '0';     
      NX_DEBUG(_debug_modifier, NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
	       "XX-dummy : override learning : %d (raw=%d)", 
	       ctx->learning ? 1 : 0, lookup->len);
    }

    NX_DEBUG( _debug_modifier, 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : [final] learning : %d", ctx->learning ? 1 : 0);


    ctx->enabled = cf->enabled;
    NX_DEBUG( _debug_modifier, 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : orig enabled : %d", ctx->enabled ? 1 : 0);

    lookup = ngx_http_get_variable(r, &enable_flag, cf->flag_enable_h);
    if (lookup && !lookup->not_found && lookup->len > 0) {
      ctx->enabled = lookup->data[0] - '0';
      NX_DEBUG( _debug_modifier, 
      NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		    "XX-dummy : override enable : %d", ctx->enabled ? 1 : 0);


    }
    NX_DEBUG( _debug_modifier, 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : [final] enabled : %d", ctx->enabled ? 1 : 0);



    /*
    ** LIBINJECTION_SQL
    */
    ctx->libinjection_sql = cf->libinjection_sql_enabled;

    NX_DEBUG( _debug_modifier, 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : orig libinjection_sql : %d", ctx->libinjection_sql ? 1 : 0);


    lookup = ngx_http_get_variable(r, &libinjection_sql_flag, cf->flag_libinjection_sql_h);

    if (lookup && !lookup->not_found && lookup->len > 0) {
      ctx->libinjection_sql = lookup->data[0] - '0';
      NX_DEBUG( _debug_modifier, 
      NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		    "XX-dummy : override libinjection_sql : %d", ctx->libinjection_sql ? 1 : 0);

    }
    NX_DEBUG( _debug_modifier, 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : [final] libinjection_sql : %d", ctx->libinjection_sql ? 1 : 0);

    /*
    ** LIBINJECTION_XSS
    */
    ctx->libinjection_xss = cf->libinjection_xss_enabled;

    NX_DEBUG( _debug_modifier, 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : orig libinjection_xss : %d", ctx->libinjection_xss ? 1 : 0);


    lookup = ngx_http_get_variable(r, &libinjection_xss_flag, cf->flag_libinjection_xss_h);
    if (lookup && !lookup->not_found && lookup->len > 0) {
      ctx->libinjection_xss = lookup->data[0] - '0';
      NX_DEBUG( _debug_modifier, 
      NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		    "XX-dummy : override libinjection_xss : %d", ctx->libinjection_xss ? 1 : 0);

    }
    NX_DEBUG( _debug_modifier, 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : [final] libinjection_xss : %d", ctx->libinjection_xss ? 1 : 0);


    /* post_action is off by default. */
    ctx->post_action = 0;
    NX_DEBUG( _debug_modifier    , 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : orig post_action : %d", ctx->post_action ? 1 : 0);

    lookup = ngx_http_get_variable(r, &post_action_flag, cf->flag_post_action_h);
    if (lookup && !lookup->not_found && lookup->len > 0) {
      ctx->post_action = lookup->data[0] - '0';
      NX_DEBUG( _debug_modifier, 
      NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		    "XX-dummy : override post_action : %d", ctx->post_action ? 1 : 0);

    }
    NX_DEBUG( _debug_modifier, 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : [final] post_action : %d", ctx->post_action ? 1 : 0);

    NX_DEBUG( _debug_modifier    , 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : orig extensive_log : %d", ctx->extensive_log ? 1 : 0);

    lookup = ngx_http_get_variable(r, &extensive_log_flag, cf->flag_extensive_log_h);
    if (lookup && !lookup->not_found && lookup->len > 0) {
      ctx->extensive_log = lookup->data[0] - '0';
      NX_DEBUG( _debug_modifier, 
      NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		    "XX-dummy : override extensive_log : %d", ctx->extensive_log ? 1 : 0);

    }
    NX_DEBUG( _debug_modifier, 
    NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		  "XX-dummy : [final] extensive_log : %d", ctx->extensive_log ? 1 : 0);


    /* the module is not enabled here */
    if (!ctx->enabled)
      return (NGX_DECLINED);
    

    if  ((r->method == NGX_HTTP_PATCH || r->method == NGX_HTTP_POST || r->method == NGX_HTTP_PUT) 
	 && !ctx->ready) {
      NX_DEBUG( _debug_mechanics, NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		"XX-dummy : body_request : before !");
      
      rc = ngx_http_read_client_request_body(r, ngx_http_dummy_payload_handler);
      /* this might happen quite often, especially with big files / 
      ** low network speed. our handler is called when headers are read, 
      ** but, often, the full body request hasn't yet, so 
      ** read client request body will return ngx_again. Then we need
      ** to return ngx_done, wait for our handler to be called once 
      ** body request arrived, and let him call core_run_phases
      ** to be able to process the request.
      */
      if (rc == NGX_AGAIN) {
	ctx->wait_for_body = 1;
	NX_DEBUG( _debug_mechanics, 
	NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		      "XX-dummy : body_request : NGX_AGAIN !");

	return (NGX_DONE);
      }
      else
	if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
	  /* 
	  ** might happen but never saw it, let the debug print.
	  */
	  ngx_log_debug(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
			"XX-dummy : SPECIAL RESPONSE !!!!");
	  return rc;
	}
    }
    else
      ctx->ready = 1;
  }
  if (ctx && ctx->ready && !ctx->over) {
    
    if ((start = times(&tmsstart)) == (clock_t)-1)
      ngx_log_debug(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		    "XX-dummy : Failed to get time");
    ngx_http_dummy_data_parse(ctx, r);
    cf->request_processed++;
    if ((end = times(&tmsend)) == (clock_t)-1)
      ngx_log_debug(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
		    "XX-dummy : Failed to get time");
    if (end - start > 10)
      ngx_log_debug(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, 
		    "[MORE THAN 10MS] times : start:%l end:%l diff:%l",
		    start, end, (end-start));
    ctx->over = 1;
    if (ctx->block || ctx->drop) {
      cf->request_blocked++;
      rc = ngx_http_output_forbidden_page(ctx, r);
      //nothing:      return (NGX_OK);
      //redirect : return (NGX_HTTP_OK);
      return rc;
    }
    else if (ctx->log)
      rc = ngx_http_output_forbidden_page(ctx, r);
  }
  NX_DEBUG(_debug_mechanics, 
	   NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
	   "NGX_FINISHED !");

  return NGX_DECLINED;
}
Esempio n. 9
0
void DynamicResult::prepareCalculations(oRunner &runner) const {
  prepareCommon(runner);
  pCard pc = runner.getCard();
  if (pc) {
    vector<pPunch> punches;
    pc->getPunches(punches);
    int np = 0;
    for (size_t k = 0; k < punches.size(); k++) {
      if (punches[k]->getTypeCode() >= 30)
        np++;
    }
    vector<int> times(np);
    vector<int> codes(np);
    vector<int> controls(np);
    int ip = 0;
    for (size_t k = 0; k < punches.size(); k++) {
      if (punches[k]->getTypeCode() >= 30) {
        times[ip] = punches[k]->getAdjustedTime();
        codes[ip] = punches[k]->getTypeCode();
        controls[ip] = punches[k]->isUsedInCourse() ? punches[k]->getControlId() : -1;
        ip++;
      }
    }
    parser.addSymbol("CardPunches", codes);
    parser.addSymbol("CardTimes", times);
    parser.addSymbol("CardControls", controls);

    pTeam t = runner.getTeam();
    if (t) {
      int leg =  runner.getLegNumber();
      t->setResultCache(oTeam::RCCCardTimes, leg, times);
      t->setResultCache(oTeam::RCCCardPunches, leg, codes);
      t->setResultCache(oTeam::RCCCardControls, leg, controls);
    }
  }
  else {
    vector<int> e;
    parser.addSymbol("CardPunches", e);
    parser.addSymbol("CardTimes", e);
    parser.addSymbol("CardControls", e);
  }

  pCourse crs = runner.getCourse(true);
  const vector<SplitData> &sp = runner.getSplitTimes(false);

  if (crs) {
    vector<int> eCrs;
    vector<int> eSplitTime;
    vector<int> eAccTime;
    eCrs.reserve(crs->getNumControls());
    eSplitTime.reserve(crs->getNumControls());
    eAccTime.reserve(crs->getNumControls());
    int start = runner.getStartTime();
    int st = runner.getStartTime();
    for (int k = 0; k < crs->getNumControls(); k++) {
      pControl ctrl = crs->getControl(k);
      if (ctrl->isSingleStatusOK()) {
        eCrs.push_back(ctrl->getFirstNumber());
        if (size_t(k) < sp.size()) {
          if (sp[k].status == SplitData::OK) {
            eAccTime.push_back(sp[k].time-start);
            eSplitTime.push_back(sp[k].time-st);
            st = sp[k].time;
          }
          else if (sp[k].status == SplitData::NoTime) {
            eAccTime.push_back(st-start);
            eSplitTime.push_back(0);
          }
          else if (sp[k].status == SplitData::Missing) {
            eAccTime.push_back(0);
            eSplitTime.push_back(-1);
          }
        }
      }
    }
    if (runner.getFinishTime() > 0) {
      eAccTime.push_back(runner.getFinishTime()-start);
      eSplitTime.push_back(runner.getFinishTime()-st);
    }
    else if (!eAccTime.empty()) {
      eAccTime.push_back(0);
      eSplitTime.push_back(-1);
    }
    
    parser.addSymbol("CourseLength", crs->getLength());
    parser.addSymbol("Course", eCrs);
    parser.addSymbol("SplitTimes", eSplitTime);
    parser.addSymbol("SplitTimesAccumulated", eAccTime);
    pTeam t = runner.getTeam();
    if (t) {
      int leg =  runner.getLegNumber();
      t->setResultCache(oTeam::RCCCourse, leg, eCrs);
      t->setResultCache(oTeam::RCCSplitTime, leg, eSplitTime);
    }
  }
  else {
    vector<int> e;
    parser.addSymbol("CourseLength", -1);
    parser.addSymbol("Course", e);
    parser.addSymbol("SplitTimes", e);
    parser.addSymbol("SplitTimesAccumulated", e);
  }

  pClass cls = runner.getClassRef();
  if (cls) {
    int nl = runner.getLegNumber();
    parser.addSymbol("ShortestClassTime", cls->getBestLegTime(nl));
  }
  vector<int> delta;
  vector<int> place;
  vector<int> after;
  runner.getSplitAnalysis(delta);
  runner.getLegTimeAfter(after);
  runner.getLegPlaces(place);

  parser.addSymbol("LegTimeDeviation", delta);
  parser.addSymbol("LegTimeAfter", after);
  parser.addSymbol("LegPlace", place);
  parser.addSymbol("Leg", runner.getLegNumber());
}
Esempio n. 10
0
int
getrusage(int who, struct rusage * rusage)
{
#ifdef WIN32

	FILETIME	starttime;
	FILETIME	exittime;
	FILETIME	kerneltime;
	FILETIME	usertime;
	ULARGE_INTEGER li;

	if (who != RUSAGE_SELF)
	{
		/* Only RUSAGE_SELF is supported in this implementation for now */
		errno = EINVAL;
		return -1;
	}

	if (rusage == (struct rusage *) NULL)
	{
		errno = EFAULT;
		return -1;
	}
	memset(rusage, 0, sizeof(struct rusage));
	if (GetProcessTimes(GetCurrentProcess(),
						&starttime, &exittime, &kerneltime, &usertime) == 0)
	{
		_dosmaperr(GetLastError());
		return -1;
	}

	/* Convert FILETIMEs (0.1 us) to struct timeval */
	memcpy(&li, &kerneltime, sizeof(FILETIME));
	li.QuadPart /= 10L;			/* Convert to microseconds */
	rusage->ru_stime.tv_sec = li.QuadPart / 1000000L;
	rusage->ru_stime.tv_usec = li.QuadPart % 1000000L;

	memcpy(&li, &usertime, sizeof(FILETIME));
	li.QuadPart /= 10L;			/* Convert to microseconds */
	rusage->ru_utime.tv_sec = li.QuadPart / 1000000L;
	rusage->ru_utime.tv_usec = li.QuadPart % 1000000L;
#else							/* all but WIN32 */

	struct tms	tms;
	int			tick_rate = CLK_TCK;	/* ticks per second */
	clock_t		u,
				s;

	if (rusage == (struct rusage *) NULL)
	{
		errno = EFAULT;
		return -1;
	}
	if (times(&tms) < 0)
	{
		/* errno set by times */
		return -1;
	}
	switch (who)
	{
		case RUSAGE_SELF:
			u = tms.tms_utime;
			s = tms.tms_stime;
			break;
		case RUSAGE_CHILDREN:
			u = tms.tms_cutime;
			s = tms.tms_cstime;
			break;
		default:
			errno = EINVAL;
			return -1;
	}
#define TICK_TO_SEC(T, RATE)	((T)/(RATE))
#define TICK_TO_USEC(T,RATE)	(((T)%(RATE)*1000000)/RATE)
	rusage->ru_utime.tv_sec = TICK_TO_SEC(u, tick_rate);
	rusage->ru_utime.tv_usec = TICK_TO_USEC(u, tick_rate);
	rusage->ru_stime.tv_sec = TICK_TO_SEC(s, tick_rate);
	rusage->ru_stime.tv_usec = TICK_TO_USEC(u, tick_rate);
#endif   /* WIN32 */

	return 0;
}
Esempio n. 11
0
int main(int argc, char *argv[]) {

    GRAPH g;
    int countTotal = 0;
    boolean writethem = FALSE, printThem = FALSE, printNew = FALSE, printOld = FALSE;
    boolean writeOld = FALSE;
    boolean first = TRUE;

    list = NULL;

    int c;
    char *name = argv[0];

    while ((c = getopt(argc, argv, "hiwnopO")) != -1) {
        switch (c) {
            case 'h':
                help(name);
                return EXIT_SUCCESS;
            case 'i':
                printNew = TRUE;
                printOld = TRUE;
                break;
            case 'n':
                printNew = TRUE;
                break;
            case 'o':
                printOld = TRUE;
                break;
            case 'p':
                printThem = TRUE;
                break;
            case 'w':
                writethem = TRUE;
                break;
            case 'O':
                writeOld = TRUE;
                break;
            default:
                usage(name);
                return EXIT_FAILURE;
        }
    }

    struct tms TMS;
    unsigned int oldtime = 0;

    while (read_pg_code(stdin, &g) != EOF) {
        countTotal++;
        int isNew = handle_new_graph(&g, &list);

        if(isNew && writethem) {
            write_pg_code(stdout, &g, first);
            first = FALSE;
        }

        if (isNew) {
            if(printNew) fprintf(stderr, "Graph %d is new.\n", countTotal);
        } else {
            if(printOld) fprintf(stderr, "Graph %d is not new.\n", countTotal);
        }

        if(isNew && printThem) {
            printGraph(stderr, &g);
        }

        if(!isNew && writeOld){
            write_pg_code(stdout, &g, first);
            first = FALSE;
        }

    }

    int countNonIso = listSize(list);

    fprintf(stderr, "Read %d graphs, of which %d pairwise not isomorph.\n", countTotal, countNonIso);

    times(&TMS);
    unsigned int savetime = oldtime + (unsigned int) TMS.tms_utime;
    fprintf(stderr, "CPU time: %.1f seconds.\n", (double) savetime / time_factor);
    
    return (0);

}
Esempio n. 12
0
// MAIN routine
main( int argc, char **argv ) {

    // Elapsed times using <times()>
    clock_t clkStart;
    clock_t clkStop;

    // CPU times for the threads
    struct tms tStart;
    struct tms tStop;

    int k;
    int i;
    int j;
    int temp;

    double max;

    vFlag = 0;
    GetParam( argc, argv );

    printf( "Starting timing ... computing ...\n" );
    clkStart = times( &tStart );

    long threadCounter;
    for( threadCounter = 0; threadCounter < M; threadCounter++ ) {

        thread_data_arry[ threadCounter ].i = 0;
        thread_data_arry[ threadCounter ].b = N;
        thread_data_arry[ threadCounter ].thread_id = threadCounter;

        printf( "\tmain: creating thread %ld\n", threadCounter );

        int threadReturnCode = pthread_create( &idThreads[ threadCounter ], NULL, rowMcol, (void *) &thread_data_arry[ threadCounter ]);

        if( threadReturnCode ) {

            printf( "ERROR; return code from pthread_create() is %d\n", threadReturnCode );

            exit( -1 );
        }
    }

    printf( "\tcompleted thread creation ... going to try to join all threads!\n" );

    // for loop processes until all threads terminate
    for( threadCounter = 0; threadCounter < M; threadCounter++ ) {

        pthread_join( idThreads[ threadCounter ], NULL );
    }

    printf( "\tall threads have terminated!\n" );
    clkStop = times( &tStop );
    printf( "Stopped timing.\n" );

    if( N < MAXN4print ) {

        PrintX();
    }

    if( vFlag == 1 ) {

        CheckX();
    }

    printf( "Elapsed time = %g ms.\n",  (float)( clkStop - clkStart ) / (float) sysconf( _SC_CLK_TCK ) * 1000 );
    printf( "The total CPU time comsumed = %g ms.\n", (float)(( tStop.tms_utime - tStart.tms_utime ) + ( tStop.tms_stime - tStart.tms_stime )) / (float)sysconf( _SC_CLK_TCK ) * 1000 );

    // Last thing that main() should do
    pthread_exit( NULL );

    return 0;
}
Esempio n. 13
0
void start_clock(Statistics *stat)
{
	stat->start_time = times(&stat->start_cpu);
}
Esempio n. 14
0
int main(void)
{
	struct itimerval it;
	struct tms buf;
	clock_t clk_tck, start_real, start_virtual, end_real, end_virtual;
	unsigned long count;
	void *data;
	int size;
	char *setting1, *setting2;
	int i;
#ifdef TEST_THREADS
	pthread_t t[TEST_THREADS];
	void *t_retval;
#endif

	data = NULL;
	size = 0x12345678;

	for (i = 0; tests[i][0]; i++) {
		const char *hash = tests[i][0];
		const char *key = tests[i][1];
		const char *setting = tests[i][2];
		const char *p;
		int ok = !setting || strlen(hash) >= 30;
		int o_size;
		char s_buf[30], o_buf[61];
		if (!setting) {
			memcpy(s_buf, hash, sizeof(s_buf) - 1);
			s_buf[sizeof(s_buf) - 1] = 0;
			setting = s_buf;
		}

		__set_errno(0);
		p = crypt(key, setting);
		if ((!ok && !errno) || strcmp(p, hash)) {
			printf("FAILED (crypt/%d)\n", i);
			return 1;
		}

		if (ok && strcmp(crypt(key, hash), hash)) {
			printf("FAILED (crypt/%d)\n", i);
			return 1;
		}

		for (o_size = -1; o_size <= (int)sizeof(o_buf); o_size++) {
			int ok_n = ok && o_size == (int)sizeof(o_buf);
			const char *x = "abc";
			strcpy(o_buf, x);
			if (o_size >= 3) {
				x = "*0";
				if (setting[0] == '*' && setting[1] == '0')
					x = "*1";
			}
			__set_errno(0);
			p = crypt_rn(key, setting, o_buf, o_size);
			if ((ok_n && (!p || strcmp(p, hash))) ||
			    (!ok_n && (!errno || p || strcmp(o_buf, x)))) {
				printf("FAILED (crypt_rn/%d)\n", i);
				return 1;
			}
		}

		__set_errno(0);
		p = crypt_ra(key, setting, &data, &size);
		if ((ok && (!p || strcmp(p, hash))) ||
		    (!ok && (!errno || p || strcmp((char *)data, hash)))) {
			printf("FAILED (crypt_ra/%d)\n", i);
			return 1;
		}
	}

	setting1 = crypt_gensalt(which[0], 12, data, size);
	if (!setting1 || strncmp(setting1, "$2a$12$", 7)) {
		puts("FAILED (crypt_gensalt)\n");
		return 1;
	}

	setting2 = crypt_gensalt_ra(setting1, 12, data, size);
	if (strcmp(setting1, setting2)) {
		puts("FAILED (crypt_gensalt_ra/1)\n");
		return 1;
	}

	(*(char *)data)++;
	setting1 = crypt_gensalt_ra(setting2, 12, data, size);
	if (!strcmp(setting1, setting2)) {
		puts("FAILED (crypt_gensalt_ra/2)\n");
		return 1;
	}

	free(setting1);
	free(setting2);
	free(data);

#if defined(_SC_CLK_TCK) || !defined(CLK_TCK)
	clk_tck = sysconf(_SC_CLK_TCK);
#else
	clk_tck = CLK_TCK;
#endif

	running = 1;
	signal(SIGALRM, handle_timer);

	memset(&it, 0, sizeof(it));
	it.it_value.tv_sec = 5;
	setitimer(ITIMER_REAL, &it, NULL);

	start_real = times(&buf);
	start_virtual = buf.tms_utime + buf.tms_stime;

	count = (char *)run((char *)0) - (char *)0;

	end_real = times(&buf);
	end_virtual = buf.tms_utime + buf.tms_stime;
	if (end_virtual == start_virtual) end_virtual++;

	printf("%.1f c/s real, %.1f c/s virtual\n",
		(float)count * clk_tck / (end_real - start_real),
		(float)count * clk_tck / (end_virtual - start_virtual));

#ifdef TEST_THREADS
	running = 1;
	it.it_value.tv_sec = 60;
	setitimer(ITIMER_REAL, &it, NULL);
	start_real = times(&buf);

	for (i = 0; i < TEST_THREADS; i++)
	if (pthread_create(&t[i], NULL, run, i + (char *)0)) {
		perror("pthread_create");
		return 1;
	}

	for (i = 0; i < TEST_THREADS; i++) {
		if (pthread_join(t[i], &t_retval)) {
			perror("pthread_join");
			continue;
		}
		if (!t_retval) continue;
		count = (char *)t_retval - (char *)0;
		end_real = times(&buf);
		printf("%d: %.1f c/s real\n", i,
			(float)count * clk_tck / (end_real - start_real));
	}
#endif

	return 0;
}
Esempio n. 15
0
Foam::word Foam::Time::findInstance
(
    const fileName& dir,
    const word& name,
    const IOobject::readOption rOpt,
    const word& stopInstance
) const
{
    // Note: if name is empty, just check the directory itself

    // check the current time directory
    if
    (
        name.empty()
      ? isDir(path()/timeName()/dir)
      :
        (
            isFile(path()/timeName()/dir/name)
         && IOobject(name, timeName(), dir, *this).headerOk()
        )
    )
    {
        if (debug)
        {
            Info<< "Time::findInstance"
                "(const fileName&, const word&, const IOobject::readOption)"
                << " : found \"" << name
                << "\" in " << timeName()/dir
                << endl;
        }

        return timeName();
    }

    // Search back through the time directories to find the time
    // closest to and lower than current time

    instantList ts = times();
    label instanceI;

    for (instanceI = ts.size()-1; instanceI >= 0; --instanceI)
    {
        if (ts[instanceI].value() <= timeOutputValue())
        {
            break;
        }
    }

    // continue searching from here
    for (; instanceI >= 0; --instanceI)
    {
        if
        (
            name.empty()
          ? isDir(path()/ts[instanceI].name()/dir)
          :
            (
                isFile(path()/ts[instanceI].name()/dir/name)
             && IOobject(name, ts[instanceI].name(), dir, *this).headerOk()
            )
        )
        {
            if (debug)
            {
                Info<< "Time::findInstance"
                    "(const fileName&, const word&, const IOobject::readOption)"
                    << " : found \"" << name
                    << "\" in " << ts[instanceI].name()/dir
                    << endl;
            }

            return ts[instanceI].name();
        }

        // Check if hit minimum instance
        if (ts[instanceI].name() == stopInstance)
        {
            if (debug)
            {
                Info<< "Time::findInstance"
                    "(const fileName&, const word&"
                    ", const IOobject::readOption, const word&)"
                    << " : hit stopInstance " << stopInstance
                    << endl;
            }

            if (rOpt == IOobject::MUST_READ)
            {
                FatalErrorIn
                (
                    "Time::findInstance"
                    "(const fileName&, const word&"
                    ", const IOobject::readOption, const word&)"
                )   << "Cannot find file \"" << name << "\" in directory "
                    << dir << " in times " << timeName()
                    << " down to " << stopInstance
                    << exit(FatalError);
            }

            return ts[instanceI].name();
        }
    }

    // not in any of the time directories, try constant

    // Note. This needs to be a hard-coded constant, rather than the
    // constant function of the time, because the latter points to
    // the case constant directory in parallel cases

    if
    (
        name.empty()
      ? isDir(path()/constant()/dir)
      :
        (
            isFile(path()/constant()/dir/name)
         && IOobject(name, constant(), dir, *this).headerOk()
        )
    )
    {
        if (debug)
        {
            Info<< "Time::findInstance"
                "(const fileName&, const word&, const IOobject::readOption)"
                << " : found \"" << name
                << "\" in " << constant()/dir
                << endl;
        }

        return constant();
    }

    if (rOpt == IOobject::MUST_READ)
    {
        FatalErrorIn
        (
            "Time::findInstance"
            "(const fileName&, const word&, const IOobject::readOption)"
        )   << "Cannot find file \"" << name << "\" in directory "
            << dir << " in times " << timeName()
            << " down to " << constant()
            << exit(FatalError);
    }

    return constant();
}
Esempio n. 16
0
int
connect_nonb(int sockfd, const struct sockaddr *saptr, socklen_t salen, int nsec)
{
	int			flags, n, conn_error;
	socklen_t	len;
	fd_set		rset, wset;
	struct timeval	tval;

	flags = fcntl(sockfd, F_GETFL, 0);
	if ( flags == -1 ) {
		error("fcntl: %s", strerror(errno));
		return FAIL;
	}
	n = fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
	if ( n == -1 ) {
		error("fcntl: %s", strerror(errno));
		return FAIL;
	}

	conn_error = 0;
	if ( (n = connect(sockfd, saptr, salen)) < 0 )
#ifdef AIX5
		if (!(errno == EINPROGRESS || errno == EEXIST || errno == 17)) {
#else
		if (errno != EINPROGRESS) {
#endif
			error("connect: %s", strerror(errno));
			return FAIL;
		}

	/* connect(2) is under progress */

	if ( n == 0 ) goto done;	/* connect(2) completed immediately */

	FD_ZERO(&rset);
	FD_SET(sockfd, &rset);
	wset = rset;
	tval.tv_sec = nsec;
	tval.tv_usec = 0;

	if ( (n = select(sockfd + 1, &rset, &wset, NULL,
						nsec ? &tval : NULL)) == 0 ) {
		close(sockfd);
		warn("select timedout(timeout = %d)", nsec);
		errno = ETIMEDOUT;
		return FAIL;
	} else if ( n == -1 ) {
		error("select: %s", strerror(errno));
		return FAIL;
	}

	if (FD_ISSET(sockfd, &rset) || FD_ISSET(sockfd, &wset)) {
		len = sizeof(conn_error);
		// refer to connect(2) EINPROGRESS error part
		if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &conn_error, &len) < 0) {
			error("getsockopt: %s", strerror(errno));
			return FAIL;
		}
	} else {
		error("select: sockfd not set");
		return FAIL;
	}

  done:
	n = fcntl(sockfd, F_SETFL, flags); /* restore file status flags */
	if ( n == -1 ) {
		error("fcntl: %s", strerror(errno));
		return FAIL;
	}

	if (conn_error) {
		close(sockfd);
		errno = conn_error;
		error("%s", strerror(errno));
		return FAIL;
	}

	return SUCCESS;
}



/*****************************************************************************/

int sb_tstat_start(tstat_t *tstat) {
	if ((tstat->cs = times(&(tstat->tms_s))) == (clock_t)-1) {
		error("%s", strerror(errno));
		return -1;
	}
	if (gettimeofday(&(tstat->tv_s), NULL) == -1) {
		error("%s", strerror(errno));
		return -1;
	}
	return 1;
}

int sb_tstat_finish(tstat_t *tstat) {
	if ((tstat->cf = times(&(tstat->tms_f))) == (clock_t)-1) {
		error("%s", strerror(errno));
		return -1;
	}
	if (gettimeofday(&(tstat->tv_f), NULL) == -1) {
		error("%s", strerror(errno));
		return -1;
	}
	return 1;
}

void sb_tstat_print(tstat_t *tstat) {
	clock_t clock_per_second;
/*	printf("gauged by gettimeofday(): Realtime:%d(ms)", */
/*			(tstat->tv_f.tv_sec - tstat->tv_s.tv_sec)*1000 +*/
/*			(tstat->tv_f.tv_usec - tstat->tv_s.tv_usec)/1000);*/
	info("gauged by gettimeofday(): Realtime:%d(s)", 
			(int)(tstat->tv_f.tv_sec - tstat->tv_s.tv_sec));

	clock_per_second = sysconf(_SC_CLK_TCK);
	info("gauged by times(): Realtime:%.2f(s), User Time %.2f(s), System Time %.2f(s)\n",
			(float)(tstat->cf - tstat->cs) / clock_per_second,
			(float)(tstat->tms_f.tms_utime - tstat->tms_s.tms_utime) / clock_per_second,
			(float)(tstat->tms_f.tms_stime - tstat->tms_s.tms_stime) / clock_per_second);
}
Esempio n. 17
0
int main(int argc,char** argv)
{
	int i,j,fd;
	int n=0;
  char buffer[100];
	int closed=0;
	int numsplitters=atoi(argv[2]);
   int id=atoi(argv[1]);
builder_List lista=builder_create_list();
	char*pipe_name;

double t1, t2, cpu_time;
struct tms tb1, tb2;
double ticspersec;
int  sum = 0;
ticspersec = (double) sysconf(_SC_CLK_TCK);
t1 = (double) times(&tb1);






struct pollfd pfds[numsplitters];


for (i=0;i<numsplitters;i++){
  	pipe_name=name_of_pipe(i,id);
	
	pfds[i].fd =open(pipe_name, O_RDONLY);
	pfds[i].events = POLLIN;
}

printf("perasa tin loopa twn splitter\n");

int k=0;

while(closed<numsplitters){

int num = poll(pfds, numsplitters, -1);
int ar=0;
if(num != 0)
        {
             if (num == -1)
             {
                 perror("poll");
                 exit(1);
             }

             for(j = 0; j < numsplitters; j++)
             {
                 if(pfds[j].revents & POLLIN)
                 {
					if(read_data (pfds[j].fd ,buffer)>0){
                    
					ar++;
								
					if (strcmp(buffer,"oulala")==0){
						closed++;	

						}
					else{
  	      			if(builder_search_list(lista,buffer)!=1)	
						builder_insert_to_end(lista,builder_create_node(buffer)); 


} }
					        
                 }
             }
         }
}


// teleiwse to diavasma apo tous splitters twra stelnw sto root

pipe_name=name_of_pipe(-1,id);


send_all(lista,pipe_name);



printf("builder %d closed \n",id);


t2 = (double) times(&tb2);
cpu_time = (double) ((tb2.tms_utime + tb2.tms_stime) -
(tb1.tms_utime + tb1.tms_stime));
//printf("Run time was %lf sec (REAL time) although we used the CPU for %lf sec (CPU time).\n",(t2 - t1)/ticspersec,cpu_time/ticspersec);
free(pipe_name);
FILE * fpa;
fpa = fopen (argv[3], "a");
fprintf(fpa,"BUILDER %d : (REAL time) %lf sec    (CPU time) %lf sec \n",id,(t2 - t1)/ticspersec,cpu_time/ticspersec);
//sleep(3);
fclose(fpa);
kill(getppid(),SIGRTMIN+2);
kill(getppid(),SIGUSR2);



}
Esempio n. 18
0
static PyObject*
py_process_time(_Py_clock_info_t *info)
{
#if defined(MS_WINDOWS)
    HANDLE process;
    FILETIME creation_time, exit_time, kernel_time, user_time;
    ULARGE_INTEGER large;
    double total;
    BOOL ok;

    process = GetCurrentProcess();
    ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time);
    if (!ok)
        return PyErr_SetFromWindowsErr(0);

    large.u.LowPart = kernel_time.dwLowDateTime;
    large.u.HighPart = kernel_time.dwHighDateTime;
    total = (double)large.QuadPart;
    large.u.LowPart = user_time.dwLowDateTime;
    large.u.HighPart = user_time.dwHighDateTime;
    total += (double)large.QuadPart;
    if (info) {
        info->implementation = "GetProcessTimes()";
        info->resolution = 1e-7;
        info->monotonic = 1;
        info->adjustable = 0;
    }
    return PyFloat_FromDouble(total * 1e-7);
#else

#if defined(HAVE_SYS_RESOURCE_H)
    struct rusage ru;
#endif
#ifdef HAVE_TIMES
    struct tms t;
    static long ticks_per_second = -1;
#endif

#if defined(HAVE_CLOCK_GETTIME) \
    && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
    struct timespec tp;
#ifdef CLOCK_PROF
    const clockid_t clk_id = CLOCK_PROF;
    const char *function = "clock_gettime(CLOCK_PROF)";
#else
    const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
    const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
#endif

    if (clock_gettime(clk_id, &tp) == 0) {
        if (info) {
            struct timespec res;
            info->implementation = function;
            info->monotonic = 1;
            info->adjustable = 0;
            if (clock_getres(clk_id, &res) == 0)
                info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
            else
                info->resolution = 1e-9;
        }
        return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
    }
#endif

#if defined(HAVE_SYS_RESOURCE_H)
    if (getrusage(RUSAGE_SELF, &ru) == 0) {
        double total;
        total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6;
        total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6;
        if (info) {
            info->implementation = "getrusage(RUSAGE_SELF)";
            info->monotonic = 1;
            info->adjustable = 0;
            info->resolution = 1e-6;
        }
        return PyFloat_FromDouble(total);
    }
#endif

#ifdef HAVE_TIMES
    if (times(&t) != (clock_t)-1) {
        double total;

        if (ticks_per_second == -1) {
#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
            ticks_per_second = sysconf(_SC_CLK_TCK);
            if (ticks_per_second < 1)
                ticks_per_second = -1;
#elif defined(HZ)
            ticks_per_second = HZ;
#else
            ticks_per_second = 60; /* magic fallback value; may be bogus */
#endif
        }

        if (ticks_per_second != -1) {
            total = (double)t.tms_utime / ticks_per_second;
            total += (double)t.tms_stime / ticks_per_second;
            if (info) {
                info->implementation = "times()";
                info->monotonic = 1;
                info->adjustable = 0;
                info->resolution = 1.0 / ticks_per_second;
            }
            return PyFloat_FromDouble(total);
        }
    }
#endif

    return floatclock(info);
#endif
}
Esempio n. 19
0
int
endnote(int xno)
{
	struct timeval tp;	
	struct timezone tzp;	
	int i,j,final_bytes,fno;
	float notepeak,*pk;
	double total;
	long *pkloc;
	struct tms timbuf;
	float peakval;
	struct stat st;
	short tisamp,*tibuf;
	float tfsamp,*tfbuf;

	fno = ABS(xno);  /* if fno is negative it means don't write
					final buffer,just pretend to */
	if(wipe_is_off[fno]) 
		_backup(fno); 
	/* else _flushbuf(fno); */
	if(!peakoff[fno]) _chkpeak(fno);
	final_bytes =  pointer[fno]  * sfclass(&sfdesc[fno]);
	
	/* This was DS's and PL's version of real time */
	/* Not used in this version */
#ifdef OLDRT

	/*  SHOULD NOT PLAY HERE -- LAST BUFFERS ALREADY PLAYED */
	if ((sfclass(&sfdesc[fno]) == SF_SHORT) && play_is_on)
		playbuf(sndbuf[fno],final_bytes/SF_SHORT);
	else if ((sfclass(&sfdesc[fno]) == SF_FLOAT) && play_is_on) {
		peakval = getpeakval(peakflag,fno);
		playfbuf(sndbuf[fno],peakval,swap[fno],nbytes/SF_FLOAT);
	}
#endif

	/* write out only fractional part of last record, god bless unix!*/
	if(pointer[fno] && (play_is_on < 2)) {
		if(xno >= 0) {
			/* Swap bytes if necessary */
			if(final_bytes && swap_bytes[fno]) {
				/* SHORT file */
				if(sfclass(&sfdesc[fno]) == SF_SHORT) {
					tibuf = (short *)sndbuf[fno]; 
					for (i=0;i<final_bytes/SF_SHORT;i++) {
						tisamp = *(tibuf+i);
						*(tibuf+i) = reverse_int2(&tisamp);
					}
				}
				/* FLOAT file */
				if(sfclass(&sfdesc[fno]) == SF_FLOAT) {
					tfbuf = (float *)sndbuf[fno]; 
					for (i=0;i<final_bytes/SF_FLOAT;i++) {
						/* 	byte_reverse4(tfbuf+i); */
						/* 	tfsamp = *(tfbuf+i); */
						/* 	*(tfbuf+i) = (float)reverse_int4(&tfsamp); */
					  	tfsamp = *(tfbuf+i);
						byte_reverse4(&tfsamp);
					  	*(tfbuf+i) = tfsamp;
					}
				}
   			}
   			if((i = write(sfd[fno],sndbuf[fno],final_bytes)) 
											!= final_bytes) {
				fprintf(stderr,
					"CMIX: Bad UNIX write, file %d, nbytes = %d\n",
					fno,i);
				perror("write");
				closesf();
   			}
   		}
   		if((filepointer[fno] += final_bytes) > originalsize[fno]) 
   		if(xno >0)  originalsize[fno] = filepointer[fno];
	}
	/* DT: 	if(play_is_on) flush_buffers(); */
	
	pk = (float *)peak[fno];
	pkloc = (long *)peakloc[fno];
	total = ((double)filepointer[fno]-headersize[fno])
					/((double)sfclass(&sfdesc[fno]))
					/(double)sfchans(&sfdesc[fno])/SR();
	
	/* _writeit(fno);  write out final record */

	for(i = 0,notepeak=0; i<sfchans(&sfdesc[fno]); i++) { 
		if(*(pk+i) > sfmaxamp(&sfm[fno],i)) {
			sfmaxamp(&sfm[fno],i) = *(pk+i);
			sfmaxamploc(&sfm[fno],i) = *(pkloc+i);
		}
		if(*(pk+i) > notepeak) notepeak = *(pk+i);
	}
	
	gettimeofday(&tp,&tzp);
	sfmaxamptime(&sfm[fno]) = tp.tv_sec;
		
	if((filepointer[fno] = lseek(sfd[fno],0L,0)) < 0) {
		fprintf(stderr,"Bad lseek to beginning of file\n");
		perror("lseek");
		closesf();
	}


	times(&timbuf);

	printf("\n(%6.2f)",(float)(
					(timbuf.tms_stime-clockin[fno].tms_stime)+
					(timbuf.tms_utime-clockin[fno].tms_utime))/60.);
	printf(" %9.4f .. %9.4f MM ",starttime[fno],total);
	
	if(!peakoff[fno]) {
		for(j=0;j<sfchans(&sfdesc[fno]);j++)
			printf(" c%d=%e",j,*(pk+j));
		printf("\n");
		if(punch[fno]) {
			printf("alter(%e,%e,%e/%e",
						(double)starttime[fno],(double)(total-starttime[fno]),
						punch[fno],notepeak);
			for(i=0; i<sfchans(&sfdesc[fno]); i++)
				printf(",1 ");
			printf(")\n");
			printf("mix(%g,%g,%g,%g/%g",
							(double)starttime[fno],(double)starttime[fno],-(double)(total-starttime[fno]),punch[fno],notepeak);
			for(i=0; i<sfchans(&sfdesc[fno]); i++)
				printf(",%d ",i);
			printf(")\n");
		}
	}

	/* Copy the updated peak stats into the SFHEADER struct for this
	   output file. (No swapping necessary.)
	*/
	memcpy(&(sfmaxampstruct(&sfdesc[fno])), &sfm[fno], sizeof(SFMAXAMP));

	/* Write header to file. */
	if (wheader(sfd[fno], &sfdesc[fno])) {
		fprintf(stderr, "endnote: bad header write\n");
		perror("write");
		closesf();
	}
	return 0;
}
Esempio n. 20
0
/*
 * get_tmp_disk - Return the total size of temporary file system on
 *    this system
 * Input: tmp_disk - buffer for the disk space size
 *        tmp_fs - pathname of the temporary file system to status,
 *		   defaults to "/tmp"
 * Output: tmp_disk - filled in with disk space size in MB, zero if error
 *         return code - 0 if no error, otherwise errno
 */
extern int
get_tmp_disk(uint32_t *tmp_disk, char *tmp_fs)
{
	int error_code = 0;
#ifdef HAVE_SYS_VFS_H
	struct statfs stat_buf;
	long   total_size;
	float page_size;
	char *tmp_fs_name = tmp_fs;

	*tmp_disk = 0;
	total_size = 0;
	page_size = (sysconf(_SC_PAGE_SIZE) / 1048576.0); /* MG per page */

	if (tmp_fs_name == NULL)
		tmp_fs_name = "/tmp";
#if defined (__sun)
	if (statfs(tmp_fs_name, &stat_buf, 0, 0) == 0) {
#else
	if (statfs(tmp_fs_name, &stat_buf) == 0) {
#endif
		total_size = (long)stat_buf.f_blocks;
	}
	else if (errno != ENOENT) {
		error_code = errno;
		error ("get_tmp_disk: error %d executing statfs on %s",
			errno, tmp_fs_name);
	}

	*tmp_disk += (uint32_t)(total_size * page_size);
#else
	*tmp_disk = 1;
#endif
	return error_code;
}

extern int get_up_time(uint32_t *up_time)
{
#if defined(HAVE_AIX) || defined(__sun)	|| defined(__APPLE__)
	clock_t tm;
	struct tms buf;

	tm = times(&buf);
	if (tm == (clock_t) -1) {
		*up_time = 0;
		return errno;
	}

	*up_time = tm / sysconf(_SC_CLK_TCK);
#elif defined(__CYGWIN__)
	FILE *uptime_file;
	char buffer[128];
	char* _uptime_path = "/proc/uptime";

	if (!(uptime_file = fopen(_uptime_path, "r"))) {
		error("get_up_time: error %d opening %s", errno, _uptime_path);
		return errno;
	}

	if (fgets(buffer, sizeof(buffer), uptime_file))
		*up_time = atoi(buffer);

	fclose(uptime_file);
#else
	/* NOTE for Linux: The return value of times() may overflow the
	 * possible range of type clock_t. There is also an offset of
	 * 429 million seconds on some implementations. We just use the
	 * simpler sysinfo() function instead. */
	struct sysinfo info;

	if (sysinfo(&info) < 0) {
		*up_time = 0;
		return errno;
	}

	*up_time = info.uptime;
#endif
	return 0;
}
Esempio n. 21
0
/*
 * It would be -so- nice just to call _wait4 and mapstatus here.
 */
int
wait4(int pid, int *status, int options, struct rusage *rp)
{
        struct  tms     before_tms;
        struct  tms     after_tms;
        siginfo_t       info;
        int             error;
        int             noptions;
	idtype_t	idtype;
 
        if ((int)status == -1 || (int)rp == -1) {
                errno = EFAULT;
                return(-1);
        }
 
        if (rp)
                memset(rp, 0, sizeof(struct rusage));
	memset(&info, 0, sizeof (siginfo_t));
        if (times(&before_tms) < 0)
                return (-1);            /* errno is set by times() */

	/*
	 * BSD's wait* routines only support WNOHANG & WUNTRACED
	 */
	if (options & ~(WNOHANG|WUNTRACED))
		return (EINVAL);
	noptions = N_WEXITED | N_WTRAPPED;
	if (options & WNOHANG)
		noptions |= N_WNOHANG;
	if (options & WUNTRACED)
		noptions |= N_WUNTRACED;	/* == N_WSTOPPED */

	/*
	 * Emulate undocumented 4.x semantics for 1186845
	 */
	if (pid < 0) {
		pid = -pid;
		idtype = P_PGID;
	} else if (pid == 0)
		idtype = P_ALL;
	else
		idtype = P_PID;

        error = _waitid(idtype, pid, &info, noptions);
        if (error == 0) {
                long diffu;  /* difference in usertime (ticks) */
                long diffs;  /* difference in systemtime (ticks) */

                if ((options & WNOHANG) && (info.si_pid == 0))
                        return (0);     /* no child found */

		if (rp) {
			if (times(&after_tms) < 0)
				return (-1);    /* errno already set by times() */
			/*
			 * The system/user time is an approximation only !!!
			 */
			diffu = after_tms.tms_cutime - before_tms.tms_cutime;
			diffs = after_tms.tms_cstime - before_tms.tms_cstime;
                	rp->ru_utime.tv_sec = diffu / HZ;
                	rp->ru_utime.tv_usec = (diffu % HZ) * (1000000 / HZ);
                	rp->ru_stime.tv_sec = diffs / HZ;
                	rp->ru_stime.tv_usec = (diffs % HZ) * (1000000 / HZ);
		}
                if (status)
                        *status = wstat(info.si_code, info.si_status);
                return (info.si_pid);
         } else {
                return (-1);            /* error number is set by waitid() */
        }
}
Esempio n. 22
0
typedef struct 
{
    unsigned long   UID;
    tPvHandle       Handle;
    tPvFrame        Frames[FRAMESCOUNT]; 
    bool            Abort;
    
} tCamera;

// global camera data
tCamera         GCamera;

#if defined(_LINUX) || defined(_QNX) || defined(_OSX)
struct tms      gTMS;
unsigned long   gT00 = times(&gTMS);

void Sleep(unsigned int time)
{
    struct timespec t,r;
    
    t.tv_sec    = time / 1000;
    t.tv_nsec   = (time % 1000) * 1000000;    
    
    while(nanosleep(&t,&r)==-1)
        t = r;
}

void SetConsoleCtrlHandler(void (*func)(int), int junk)
{
    signal(SIGINT, func);
Esempio n. 23
0
File: main.c Progetto: shaze/wcdest
int main(int argc, char *argv[]) {
  struct tms usage;
  FILE *finp;
  int i,j, ticks;
  int numinfirst;
  char chkfile[255];

  i=0;
  dump_file=NULL;

  do_cluster=do_pairwise_cluster;
  srandom(563573);
  bzero(&prog_opts,sizeof(ProgOptionsType));
  outf=stdout;
  // set default distance function
  dist = d2;
  distpair= d2pair;
#ifdef MPI
  MPI_Init(&argc, &argv);
  MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
  MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  MPI_Comm_rank(MPI_COMM_WORLD, &myid);
#endif


  if(myid==0) { // Master
    process_options(argc, argv);
  } else {
    process_slave_options(argc, argv);
  }

  if (prog_opts.show_version || (argc==1)) {
      if (myid==0) printf("Version \n%s\n",version);
#ifdef MPI      
      MPI_Finalize();
#endif
      exit(0);
    }


  // Allocate space for the RC table for big words
  rc_big = calloc(BIG_WORD_TSIZE, sizeof(SeqElt));

  // work is an array of work blocks. If non-parallel, there'll only
  // be one. work[0] acts a template

  work = (WorkPtr) calloc(num_threads,sizeof(WorkBlock));
  work->filename = argv[optind];
  work->index    = NULL;


  if(prog_opts.do_dump) dump_file = fopen(prog_opts.dname,"w");

#ifdef MPI
  if (numprocs > 1)  
    if (myid>0) {  // slaves
      if (prog_opts.split) {
	MPI_Finalize();
	return 0;
      }
      handleMPISlaveSetup(&num_seqs);
      initialise(work, prog_opts.edfile);
      internalTest();

      perform_clustering(work);
      transmitMPISlaveResponse(work);
      if (prog_opts.show_perf)     show_performance(outf);
      MPI_Finalize();
      exit(0);
    }   
#else
  if (numprocs > 1) {
    printf("This version of wcd is not compiled with MPI\n");
    printf("You cannot run it with a multiple processes\n");
    printf("Either only run it with one process or do a \n");
    printf("  ./configure --enable-mpi\n");
    printf("  make clean\n");
    printf("  make \n");
    exit(5);
  }
#endif

  // work out number of sequences
  // if the user has specified a value for num_seqs then
  // use that, else use the number of sequences in the file
  num_seqs = count_seqs(argv[optind], &data_size)+reindex_value;

  seq = (SeqPtr *) calloc(num_seqs,sizeof(SeqPtr));
  seqInfo     = (SeqInfoPtr) calloc(num_seqs,sizeof(SeqInfoStruct));
  tree= (UnionFindPtr) calloc(num_seqs,sizeof(UnionFindStruct));
  data= (SeqPtr)  calloc(data_size,sizeof(SeqElt));
  init_dummy_sequences();
#ifndef AUXINFO
  seqID = (SeqIDPtr) calloc(num_seqs,sizeof(SeqIDStruct));
#endif
  if (seq == NULL) {
    perror("SeqStruct allocation");
    exit(50);
  }
  numinfirst = global_i_end = num_seqs;
  global_j_beg = 0;
  // if merging, need to check the other file too
  if (prog_opts.domerge || prog_opts.doadd ) {
    global_j_beg = global_i_end;
    num_seqs = handleMerge(argv[optind+2], num_seqs);
    if (prog_opts.doadd) global_i_end = num_seqs; 
  }

  initialise(work, prog_opts.edfile);
  if (data == NULL) {
    sprintf(chkfile,"Main data store (%d bytes)",data_size);
    perror(chkfile);
    exit(51);
  }
  for(i=0; i<num_seqs; i++) seqInfo[i].flag=0;
  // reopen sequence file for reading
  finp = fopen(argv[optind],"r");
  if (finp == NULL)  {
    perror(argv[optind]);
    exit(51);
  }
  // Some messy stuff to hande auxiliary options
  // Skip to next comment on first reading
  if (prog_opts.pairwise==1) {
    sscanf(argv[optind+1], "%d", &i);
    sscanf(argv[optind+2], "%d", &j);
    show_pairwise(finp,i,j);
    return 0;
  }
  if (prog_opts.statgen) {
    compared2nummatches(finp,prog_opts.statgen);
    return 0;
  }
  if (prog_opts.range) {
    sscanf(argv[optind+1], "%d", &global_i_beg);
    sscanf(argv[optind+2], "%d", &global_i_end);
  }     
  if (prog_opts.show_comp==41) {
    char * fname; fname = malloc(255);
    sscanf(argv[optind+1], "%s", fname);
    read_sequences(finp,reindex_value,num_seqs); 
    checkfile = fopen(fname,"r");
    sscanf(argv[optind+2], "%d", &j);
    while (fscanf(checkfile,"%d", &i) != -1) {
    	  do_compare(finp,i,j,1);
}
    return 0;
  }

  if (prog_opts.show_comp) {
    sscanf(argv[optind+1], "%d", &i);
    sscanf(argv[optind+2], "%d", &j);
    //printf("Comparing %d and %d of %d flag %d\n",i,j,num_seqs,prog_opts.flag);
    read_sequences(finp,reindex_value,num_seqs); 
    do_compare(finp,i,j,prog_opts.flag);
    return 0;
  }
  if (prog_opts.show_index) {
    show_sequence(finp, prog_opts.index,prog_opts.flag);
    return 0;
  }
  // Now read in the sequences
  if (do_cluster == do_pairwise_cluster||do_cluster==do_MPImaster_cluster||do_cluster == do_suffix_cluster) 
    read_sequences(finp,reindex_value,numinfirst);
  else
    init_sequences(finp,reindex_value,numinfirst);
  fclose(finp);
  //printf("%d Allocated %d, start=%d, last=%d\n",num_seqs,data_size,data,seq[num_seqs-1].seq);

  if (prog_opts.split) {
    process_split(prog_opts.clfname1, prog_opts.split);
#ifdef MPI
    MPI_Finalize();
#endif
    return 0;
  }
  if (prog_opts.consfname1) process_constraints(prog_opts.consfname1,0);
  if (prog_opts.clustercomp) {
    cluster_compare(argv[optind+1]);
    return 0;
  }
  // If merging or adding need to open the second sequence file
  if (prog_opts.domerge || prog_opts.doadd) {
    finp = fopen(argv[optind+2], "r");
    if (finp == NULL)  {
      perror(argv[optind]);
      exit(1);
    }
    if (do_cluster == do_pairwise_cluster)
      read_sequences(finp,numinfirst+reindex_value,num_seqs);
    else
      init_sequences(finp,numinfirst+reindex_value,num_seqs);
    get_clustering(argv[optind+1],0);
    if (prog_opts.domerge) get_clustering(argv[optind+3],numinfirst);
  }
  if (prog_opts.init_cluster) get_clustering(prog_opts.clfname1, 0);
  if (prog_opts.recluster)
    reclustering(work,prog_opts.clfname2);
  else {
    // This really assumes there is only one thread for suffix
    if (prog_opts.pairwise==2) {
      matrix_compare(finp);
      return 0;
    }
    work->workflag = prog_opts.noninterleavednlc;//kludge for suffixarray
    global_j_end = num_seqs;
    perform_clustering(work);
#ifdef MPI
    if (myid>0) transmitMPISlaveResponse(work);
#endif
  }
  if (prog_opts.show_ext)      show_EXT(outf);
  if (prog_opts.show_histo)    show_histogram(work);
  if (prog_opts.show_clust&1) show_clusters(outf); 
  if (prog_opts.show_clust&8) 
    produce_clusters(prog_opts.clthresh,prog_opts.dirname);
  if (prog_opts.show_perf)     show_performance(outf);
  if (prog_opts.do_dump) {
    strcpy(chkfile,prog_opts.dname);
    strcat(chkfile,"-FIN");
    fclose(dump_file);
    dump_file = fopen(chkfile,"w");
    times(&usage);
    ticks = sysconf(_SC_CLK_TCK);
    fprintf(dump_file,"Completed %ld %ld", usage.tms_utime/ticks, usage.tms_stime*1000/ticks);
    fclose(dump_file);
  }
  if (prog_opts.show_version) fprintf(outf,"\n%s\n",version);
  fclose(outf);
#ifdef MPI
  MPI_Finalize();
#endif
  exit(0);
}
Esempio n. 24
0
std::vector<int> ParameterFileSimple::getTimes() const {
   std::vector<int> times(1,0);
   return times;
}
Esempio n. 25
0
int main(int argc, char*argv[])
{
	char *tcp_device;
	int fd, i;
	struct svrqueryparam qpar;
	char *pval;
	struct timeval uptime;
	clock_t now;
	int fl;
	int a_flag, n_flag, v_flag;

	(prog_name=strrchr(argv[0], '/')) ? prog_name++ : (prog_name=argv[0]);

	a_flag= 0;
	n_flag= 0;
	v_flag= 0;
	while ((fl= getopt(argc, argv, "?anv")) != -1)
	{
		switch(fl)
		{
		case '?':
			usage();
		case 'a':
			a_flag= 1;
			break;
		case 'n':
			n_flag= 1;
			break;
		case 'v':
			v_flag= 1;
			break;
		default:
			fprintf(stderr, "%s: getopt failed: '%c'\n", 
				prog_name, fl);
			exit(1);
		}
	}
	inclListen= !!a_flag;
	numerical= !!n_flag;
	verbose= !!v_flag;

	tcp_device= TCP_DEVICE;
	if ((fd= open(tcp_device, O_RDWR)) == -1)
	{
		fprintf(stderr, "%s: unable to open '%s': %s\n", prog_name,
			tcp_device, strerror(errno));
		exit(1);
	}

	qpar.param = "tcp_conn_table";
	qpar.psize = strlen(qpar.param);
	qpar.value = values;
	qpar.vsize = sizeof(values);
	if (ioctl(fd, NWIOQUERYPARAM, &qpar) == -1)
	{
		fprintf(stderr, "%s: queryparam failed: %s\n", prog_name,
			strerror(errno));
		exit(1);
	}
	pval= values;
	if (paramvalue(&pval, tcp_conn_table, sizeof(tcp_conn_table)) !=
		sizeof(tcp_conn_table))
	{
		fprintf(stderr,
			"%s: unable to decode the results from queryparam\n",
			prog_name);
		exit(1);
	}

#ifdef __minix_vmd
	/* Get the uptime in clock ticks. */
	if (sysutime(UTIME_UPTIME, &uptime) == -1)
	{
		fprintf(stderr, "%s: sysutime failed: %s\n", prog_name,
			strerror(errno));
		exit(1);
	}
	now= uptime.tv_sec * HZ + (uptime.tv_usec*HZ/1000000);
#else	/* Minix 3 */
	now= times(NULL);
#endif

	for (i= 0; i<TCP_CONN_NR; i++)
		print_conn(i, now);
	exit(0);
}
Esempio n. 26
0
bool p_isolation_metrics(QStringList timeseries_list, QString firings_path, QString metrics_out_path, QString pair_metrics_out_path, P_isolation_metrics_opts opts)
{
    qDebug().noquote() << "Starting p_isolation_metrics";

    DiskReadMda32 X(2, timeseries_list);
    Mda firings(firings_path);

    int M = X.N1();
    int T = opts.clip_size;

    QMap<int, P_isolation_metrics::ClusterData> cluster_data;

    QVector<double> times(firings.N2());
    QVector<int> labels(firings.N2());
    for (bigint i = 0; i < firings.N2(); i++) {
        times[i] = firings.value(1, i);
        labels[i] = firings.value(2, i);
    }

    QSet<int> used_cluster_numbers_set;
    for (bigint i = 0; i < labels.count(); i++) {
        used_cluster_numbers_set.insert(labels[i]);
    }
    if (!opts.cluster_numbers.isEmpty()) {
        used_cluster_numbers_set = used_cluster_numbers_set.intersect(opts.cluster_numbers.toSet());
    }
    QList<int> cluster_numbers = used_cluster_numbers_set.toList();
    qSort(cluster_numbers);

    qDebug().noquote() << "Computing cluster metrics...";
#pragma omp parallel for
    for (int jj = 0; jj < cluster_numbers.count(); jj++) {
        DiskReadMda32 X0;
        QVector<double> times_k;
        int k;
        P_isolation_metrics_opts opts0;
#pragma omp critical
        {
            X0 = X;
            k = cluster_numbers[jj];
            for (bigint i = 0; i < labels.count(); i++) {
                if (labels[i] == k)
                    times_k << times[i];
            }
            opts0 = opts;
        }

        QJsonObject tmp = P_isolation_metrics::get_cluster_metrics(X0, times_k, opts0);

#pragma omp critical
        {
            P_isolation_metrics::ClusterData CD;
            CD.times = times_k;
            CD.cluster_metrics = tmp;
            cluster_data[k] = CD;
        }
    }

    //compute templates
    qDebug().noquote() << "Computing templates...";
    Mda32 templates0;
    {
        QSet<int> cluster_numbers_set = cluster_numbers.toSet();
        QVector<double> times;
        QVector<int> labels;
        for (bigint i = 0; i < firings.N2(); i++) {
            bigint label0 = (bigint)firings.value(2, i);
            if (cluster_numbers_set.contains(label0)) {
                //inds << i;
                times << firings.value(1, i);
                labels << label0;
            }
        }

        //templates0 = compute_templates_0(X, times, labels, opts.clip_size);
        templates0 = compute_templates_in_parallel(X, times, labels, opts.clip_size);
    }

    qDebug().noquote() << "Determining pairs to compare...";
    QJsonArray cluster_pairs;
    int num_comparisons_per_cluster = 10;
    QSet<QString> pairs_to_compare = P_isolation_metrics::get_pairs_to_compare(templates0, num_comparisons_per_cluster, cluster_numbers, opts);
    QList<QString> pairs_to_compare_list = pairs_to_compare.toList();
    qSort(pairs_to_compare_list);
#pragma omp parallel for
    for (int jj = 0; jj < pairs_to_compare_list.count(); jj++) {
        QString pairstr;
        int k1, k2;
        QVector<double> times_k1, times_k2;
        P_isolation_metrics_opts opts0;
        DiskReadMda32 X0;
#pragma omp critical
        {
            pairstr = pairs_to_compare_list[jj];
            QStringList vals = pairstr.split("-");
            k1 = vals[0].toInt();
            k2 = vals[1].toInt();
            times_k1 = cluster_data.value(k1).times;
            times_k2 = cluster_data.value(k2).times;
            opts0 = opts;
            X0 = X;
        }

        QJsonObject pair_metrics = P_isolation_metrics::get_pair_metrics(X0, times_k1, times_k2, opts0);

#pragma omp critical
        {
            QJsonObject tmp;
            tmp["label"] = QString("%1,%2").arg(k1).arg(k2);
            tmp["metrics"] = pair_metrics;
            double overlap = pair_metrics["overlap"].toDouble();
            if (1 - overlap < cluster_data[k1].isolation) {
                cluster_data[k1].isolation = 1 - overlap;
                cluster_data[k1].overlap_cluster = k2;
            }
            if (1 - overlap < cluster_data[k2].isolation) {
                cluster_data[k2].isolation = 1 - overlap;
                cluster_data[k2].overlap_cluster = k1;
            }
            cluster_pairs.push_back(tmp);
        }
    }

    if (opts.compute_bursting_parents) {
        qDebug().noquote() << "Computing bursting parents...";
        for (int jj = 0; jj < cluster_numbers.count(); jj++) {
            int k1 = cluster_numbers[jj];
            Mda32 template1;
            templates0.getChunk(template1, 0, 0, k1 - 1, M, T, 1);
            cluster_data[k1].bursting_parent = 0;
            for (int kk = 0; kk < cluster_numbers.count(); kk++) {
                int k2 = cluster_numbers[kk];
                Mda32 template2;
                templates0.getChunk(template2, 0, 0, k2 - 1, M, T, 1);
                if (P_isolation_metrics::is_bursting_parent_candidate(template1, template2, opts)) {
                    bool verbose = false;
                    if (P_isolation_metrics::test_bursting_timing(cluster_data[k1].times, cluster_data[k2].times, opts, verbose)) {
                        cluster_data[k1].bursting_parent = k2;
                    }
                }
            }
        }
    }

    qDebug().noquote() << "preparing clusters array";
    QJsonArray clusters;
    foreach (int k, cluster_numbers) {
        QJsonObject tmp;
        tmp["label"] = k;
        cluster_data[k].cluster_metrics["isolation"] = cluster_data[k].isolation;
        cluster_data[k].cluster_metrics["overlap_cluster"] = cluster_data[k].overlap_cluster;
        if (opts.compute_bursting_parents)
            cluster_data[k].cluster_metrics["bursting_parent"] = cluster_data[k].bursting_parent;
        tmp["metrics"] = cluster_data[k].cluster_metrics;
        clusters.push_back(tmp);
    }
Esempio n. 27
0
static void perf_get_info(FB_API_HANDLE* handle, P* perf)
{
/**************************************
 *
 *	P E R F _ g e t _ i n f o
 *
 **************************************
 *
 * Functional description
 *	Acquire timing and performance information.  Some info comes
 *	from the system and some from the database.
 *
 **************************************/
	SSHORT buffer_length, item_length;
	ISC_STATUS_ARRAY jrd_status;
#ifdef HAVE_GETTIMEOFDAY
	struct timeval tp;
#else
	struct timeb time_buffer;
#define LARGE_NUMBER 696600000	// to avoid overflow, get rid of decades)
#endif

	// If there isn't a database, zero everything out

	if (!*handle) {
		memset(perf, 0, sizeof(PERF));
	}

	// Get system time

	times(&perf->perf_times);

#ifdef HAVE_GETTIMEOFDAY
	GETTIMEOFDAY(&tp);
	perf->perf_elapsed = tp.tv_sec * 100 + tp.tv_usec / 10000;
#else
	ftime(&time_buffer);
	perf->perf_elapsed = (time_buffer.time - LARGE_NUMBER) * 100 + (time_buffer.millitm / 10);
#endif

	if (!*handle)
		return;

	SCHAR buffer[256];
	buffer_length = sizeof(buffer);
	item_length = sizeof(items);
	isc_database_info(jrd_status, handle, item_length, items, buffer_length, buffer);

	const char* p = buffer;

	while (true)
		switch (*p++)
		{
		case isc_info_reads:
			perf->perf_reads = get_parameter(&p);
			break;

		case isc_info_writes:
			perf->perf_writes = get_parameter(&p);
			break;

		case isc_info_marks:
			perf->perf_marks = get_parameter(&p);
			break;

		case isc_info_fetches:
			perf->perf_fetches = get_parameter(&p);
			break;

		case isc_info_num_buffers:
			perf->perf_buffers = get_parameter(&p);
			break;

		case isc_info_page_size:
			perf->perf_page_size = get_parameter(&p);
			break;

		case isc_info_current_memory:
			perf->perf_current_memory = get_parameter(&p);
			break;

		case isc_info_max_memory:
			perf->perf_max_memory = get_parameter(&p);
			break;

		case isc_info_end:
			return;

		case isc_info_error:
			switch (p[2])
			{
			 case isc_info_marks:
				perf->perf_marks = 0;
				break;
			case isc_info_current_memory:
				perf->perf_current_memory = 0;
				break;
			case isc_info_max_memory:
				perf->perf_max_memory = 0;
				break;
			}

			{
				const SLONG temp = isc_vax_integer(p, 2);
				fb_assert(temp <= MAX_SSHORT);
				p += temp + 2;
			}

			perf->perf_marks = 0;
			break;

		default:
			return;
		}
}
Esempio n. 28
0
int main(int argc, char *argv[])
{
   int ii;
   double ttim, utim, stim, tott;
   struct tms runtimes;
   subharminfo **subharminfs;
   accelobs obs;
   infodata idata;
   GSList *cands = NULL;
   Cmdline *cmd;

   /* Prep the timer */

   tott = times(&runtimes) / (double) CLK_TCK;

   /* Call usage() if we have no command line arguments */

   if (argc == 1) {
      Program = argv[0];
      printf("\n");
      usage();
      exit(1);
   }

   /* Parse the command line using the excellent program Clig */

   cmd = parseCmdline(argc, argv);

#ifdef DEBUG
   showOptionValues();
#endif

   printf("\n\n");
   printf("    Fourier-Domain Acceleration Search Routine\n");
   printf("               by Scott M. Ransom\n\n");

   /* Create the accelobs structure */
   create_accelobs(&obs, &idata, cmd, 1);

   /* Zap birdies if requested and if in memory */
   if (cmd->zaplistP && !obs.mmap_file && obs.fft) {
      int numbirds;
      double *bird_lobins, *bird_hibins, hibin;

      /* Read the Standard bird list */
      numbirds = get_birdies(cmd->zaplist, obs.T, cmd->baryv,
                             &bird_lobins, &bird_hibins);

      /* Zap the birdies */
      printf("Zapping them using a barycentric velocity of %.5gc.\n\n", cmd->baryv);
      hibin = obs.N / 2;
      for (ii = 0; ii < numbirds; ii++) {
         if (bird_lobins[ii] >= hibin)
            break;
         if (bird_hibins[ii] >= hibin)
            bird_hibins[ii] = hibin - 1;
         zapbirds(bird_lobins[ii], bird_hibins[ii], NULL, obs.fft);
      }

      free(bird_lobins);
      free(bird_hibins);
   }

   printf("Searching with up to %d harmonics summed:\n",
          1 << (obs.numharmstages - 1));
   printf("  f = %.1f to %.1f Hz\n", obs.rlo / obs.T, obs.rhi / obs.T);
   printf("  r = %.1f to %.1f Fourier bins\n", obs.rlo, obs.rhi);
   printf("  z = %.1f to %.1f Fourier bins drifted\n\n", obs.zlo, obs.zhi);

   /* Generate the correlation kernels */

   printf("Generating correlation kernels:\n");
   subharminfs = create_subharminfos(obs.numharmstages, (int) obs.zhi);
   printf("Done generating kernels.\n\n");
   printf("Starting the search.\n");
   /* Don't use the *.txtcand files on short in-memory searches */
   if (!obs.dat_input) {
      printf("  Working candidates in a test format are in '%s'.\n\n",
             obs.workfilenm);
   }

   /* Start the main search loop */

   {
      double startr = obs.rlo, lastr = 0, nextr = 0;
      ffdotpows *fundamental;

      while (startr + ACCEL_USELEN * ACCEL_DR < obs.highestbin) {
         /* Search the fundamental */
         print_percent_complete(startr - obs.rlo,
                                obs.highestbin - obs.rlo, "search", 0);
         nextr = startr + ACCEL_USELEN * ACCEL_DR;
         lastr = nextr - ACCEL_DR;
         fundamental = subharm_ffdot_plane(1, 1, startr, lastr,
                                           &subharminfs[0][0], &obs);
         cands = search_ffdotpows(fundamental, 1, &obs, cands);

         if (obs.numharmstages > 1) {   /* Search the subharmonics */
            int stage, harmtosum, harm;
            ffdotpows *subharmonic;

            for (stage = 1; stage < obs.numharmstages; stage++) {
               harmtosum = 1 << stage;
               for (harm = 1; harm < harmtosum; harm += 2) {
                  subharmonic = subharm_ffdot_plane(harmtosum, harm, startr, lastr,
                                                    &subharminfs[stage][harm - 1],
                                                    &obs);
                  add_ffdotpows(fundamental, subharmonic, harmtosum, harm);
                  free_ffdotpows(subharmonic);
               }
               cands = search_ffdotpows(fundamental, harmtosum, &obs, cands);
            }
         }
         free_ffdotpows(fundamental);
         startr = nextr;
      }
      print_percent_complete(obs.highestbin - obs.rlo,
                             obs.highestbin - obs.rlo, "search", 0);
   }

   printf("\n\nDone searching.  Now optimizing each candidate.\n\n");
   free_subharminfos(obs.numharmstages, subharminfs);

   {                            /* Candidate list trimming and optimization */
      int numcands;
      GSList *listptr;
      accelcand *cand;
      fourierprops *props;


      numcands = g_slist_length(cands);

      if (numcands) {

         /* Sort the candidates according to the optimized sigmas */

         cands = sort_accelcands(cands);

         /* Eliminate (most of) the harmonically related candidates */
         if ((cmd->numharm > 1) && !(cmd->noharmremoveP))
             eliminate_harmonics(cands, &numcands);

         /* Now optimize each candidate and its harmonics */

         print_percent_complete(0, 0, NULL, 1);
         listptr = cands;
         for (ii = 0; ii < numcands; ii++) {
            print_percent_complete(ii, numcands, "optimization", 0);
            cand = (accelcand *) (listptr->data);
            optimize_accelcand(cand, &obs);
            listptr = listptr->next;
         }
         print_percent_complete(ii, numcands, "optimization", 0);

         /* Calculate the properties of the fundamentals */

         props = (fourierprops *) malloc(sizeof(fourierprops) * numcands);
         listptr = cands;
         for (ii = 0; ii < numcands; ii++) {
            cand = (accelcand *) (listptr->data);
            /* In case the fundamental harmonic is not significant,  */
            /* send the originally determined r and z from the       */
            /* harmonic sum in the search.  Note that the derivs are */
            /* not used for the computations with the fundamental.   */
            calc_props(cand->derivs[0], cand->r, cand->z, 0.0, props + ii);
            /* Override the error estimates based on power */
            props[ii].rerr = (float) (ACCEL_DR) / cand->numharm;
            props[ii].zerr = (float) (ACCEL_DZ) / cand->numharm;
            listptr = listptr->next;
         }

         /* Write the fundamentals to the output text file */

         output_fundamentals(props, cands, &obs, &idata);

         /* Write the harmonics to the output text file */

         output_harmonics(cands, &obs, &idata);

         /* Write the fundamental fourierprops to the cand file */

         obs.workfile = chkfopen(obs.candnm, "wb");
         chkfwrite(props, sizeof(fourierprops), numcands, obs.workfile);
         fclose(obs.workfile);
         free(props);
         printf("\n\n");
      } else {
         printf("No candidates above sigma = %.2f were found.\n\n", obs.sigma);
      }
   }

   /* Finish up */

   printf("Searched the following approx numbers of independent points:\n");
   printf("  %d harmonic:   %9lld\n", 1, obs.numindep[0]);
   for (ii = 1; ii < obs.numharmstages; ii++)
      printf("  %d harmonics:  %9lld\n", 1 << ii, obs.numindep[ii]);

   printf("\nTiming summary:\n");
   tott = times(&runtimes) / (double) CLK_TCK - tott;
   utim = runtimes.tms_utime / (double) CLK_TCK;
   stim = runtimes.tms_stime / (double) CLK_TCK;
   ttim = utim + stim;
   printf("    CPU time: %.3f sec (User: %.3f sec, System: %.3f sec)\n",
          ttim, utim, stim);
   printf("  Total time: %.3f sec\n\n", tott);

   printf("Final candidates in binary format are in '%s'.\n", obs.candnm);
   printf("Final Candidates in a text format are in '%s'.\n\n", obs.accelnm);

   free_accelobs(&obs);
   g_slist_foreach(cands, free_accelcand, NULL);
   g_slist_free(cands);
   return (0);
}
Esempio n. 29
0
static int Ptimes(lua_State *L)			/** times() */
{
	struct mytimes t;
	t.elapsed = times(&t.t);
	return doselection(L, 1, Stimes, Ftimes, &t);
}
Esempio n. 30
0
clock_t get_now_time(void)
{
    return times(&t);
}