当前位置: 首页>>代码示例>>Python>>正文


Python nonportable.getruntime函数代码示例

本文整理汇总了Python中nonportable.getruntime函数的典型用法代码示例。如果您正苦于以下问题:Python getruntime函数的具体用法?Python getruntime怎么用?Python getruntime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了getruntime函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: safe_check_subprocess

def safe_check_subprocess(code):
  """
  <Purpose>
    Runs safe_check() in a subprocess. This is done because the AST safe_check()
    creates uses a large amount of RAM. By running safe_check() in a subprocess
    we can guarantee that the memory will be reclaimed when the process ends.
  
  <Arguments>
    code: See safe_check.
    
  <Exceptions>
    As with safe_check.
  
  <Return>
    See safe_check.
  """
  
  # Get the path to safe_check.py by using the original start directory of python
  path_to_safe_check = os.path.join(repy_constants.REPY_START_DIR, "safe_check.py")
  
  # Start a safety check process, reading from the user code and outputing to a pipe we can read
  proc = subprocess.Popen([sys.executable, path_to_safe_check],stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  
  # Write out the user code, close so the other end gets an EOF
  proc.stdin.write(code)
  proc.stdin.close()
  
  # Wait for the process to terminate
  starttime = nonportable.getruntime()

  # Only wait up to EVALUTATION_TIMEOUT seconds before terminating
  while nonportable.getruntime() - starttime < EVALUTATION_TIMEOUT:
    # Did the process finish running?
    if proc.poll() != None:
      break;
    time.sleep(0.02)
  else:
    # Kill the timed-out process
    try:
      harshexit.portablekill(proc.pid)
    except:
      pass
    raise Exception, "Evaluation of code safety exceeded timeout threshold \
                    ("+str(nonportable.getruntime() - starttime)+" seconds)"
  
  # Read the output and close the pipe
  output = proc.stdout.read()
  proc.stdout.close()
  
  # Check the output, None is success, else it is a failure
  if output == "None":
    return True
  
  # If there is no output, this is a fatal error condition
  elif output == "":
    raise Exception, "Fatal error while evaluating code safety!"
    
  else:
    # Raise the error from the output
    raise exception_hierarchy.SafeException, output
开发者ID:pinaksaha,项目名称:reference_monitor,代码行数:60,代码来源:safe.py

示例2: should_start_waitable_thread

def should_start_waitable_thread(threadid, threadname):
  # first time!   Let's init!
  if threadid not in thread_starttime:
    thread_waittime[threadid] = minwaittime
    thread_starttime[threadid] = 0.0

  # If asking about advert thread and node_reset_config specifies to reset it,
  # then return True
  if threadid == 'advert' and node_reset_config['reset_advert']:
    # Before returning, turn off the reset flag
    node_reset_config['reset_advert'] = False
    return True
  
  # If it has been started, and the elapsed time is too short, always return
  # False to say it shouldn't be restarted
  if thread_starttime[threadid] and nonportable.getruntime() - thread_starttime[threadid] < thread_waittime[threadid]:
    return False
    
  for thread in threading.enumerate():
    if threadname in str(thread):
      # running now.   If it's run for a reasonable time, let's reduce the 
      # wait time...
      if nonportable.getruntime() - thread_starttime[threadid] > reasonableruntime:
        thread_waittime[threadid] = max(minwaittime, thread_waittime[threadid]-decreaseamount)
      return False
  else:
    return True
开发者ID:JakobKallin,项目名称:Seastorm-Preview,代码行数:27,代码来源:nmmain.py

示例3: lookup_timedout

def lookup_timedout():
    """
    <Purpose>
       Waits for lookup_done_event and notifies the folks on the
       notify_list (global var) of the lookup timeout.

    <Arguments>
        None.

    <Exceptions>
        None.

    <Side Effects>
        Sends an email to the notify_list folks

    <Returns>
        None.
    """
    integrationtestlib.log("in lookup_timedout()")
    notify_msg = "Centralized lookup failed -- lookup_timedout() fired after 30 sec."
    
    # wait for the event to be set, timeout after 30 minutes
    wait_time = 1800
    tstamp_before_wait = nonportable.getruntime()
    lookup_done_event.wait(wait_time)
    tstamp_after_wait = nonportable.getruntime()

    t_waited = tstamp_after_wait - tstamp_before_wait
    if abs(wait_time - t_waited) < 5:
        notify_msg += " And lookup stalled for over 30 minutes (max timeout value)."
    else:
        notify_msg += " And lookup stalled for " + str(t_waited) + " seconds"

    integrationtestlib.notify(notify_msg)
    return
开发者ID:aot221,项目名称:monitor_script,代码行数:35,代码来源:centralizedputget.py

示例4: safe_check

def safe_check(code):
    """Check the code to be safe."""
    return True
    # NOTE: This code will not work in Windows Mobile due to the reliance on subprocess
    
    # Get the path to safe_check.py by using the original start directory of python
    path_to_safe_check = os.path.join(repy_constants.REPY_START_DIR, "safe_check.py")
    
    # Start a safety check process, reading from the user code and outputing to a pipe we can read
    proc = subprocess.Popen(["python", path_to_safe_check],stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    
    # Write out the user code, close so the other end gets an EOF
    proc.stdin.write(code)
    proc.stdin.close()
    
    # Wait for the process to terminate
    starttime = nonportable.getruntime()
    status = None
    
    # Only wait up to EVALUTATION_TIMEOUT seconds before terminating
    while status == None and (nonportable.getruntime() - starttime < EVALUTATION_TIMEOUT):
      status = proc.poll()
      time.sleep(0.02)
      
    else:
      # Check if the process is still running
      if status == None:
        # Try to terminate the external process
        try:
          harshexit.portablekill(proc.pid)
        except:
          pass
      
        # Raise an exception
        raise Exception, "Evaluation of code safety exceeded timeout threshold ("+str(nonportable.getruntime() - starttime)+" seconds)"
    
    
    # Read the output and close the pipe
    output = proc.stdout.read()
    proc.stdout.close()
    
    # Check the output, None is success, else it is a failure
    if output == "None":
      return True
    
    # If there is no output, this is a fatal error condition
    elif output == "":
      raise Exception, "Fatal error while evaluating code safety!"
      
    else:
      # Raise the error from the output
      raise exception_hierarchy.SafeException, output
开发者ID:Lind-Project,项目名称:nacl_repy,代码行数:52,代码来源:safe.py

示例5: measure_write

def measure_write(write_file_obj, blocksize, totalbytes, use_sync=False):
  """
  <Purpose>
    Attempts to measure the disk write rate by writing totalbytes bytes to a
    temporary file (performing a flush each time blocksize many bytes have been
    written), timing how long it took, and dividing num_bytes by the time
    to get the write rate.

  <Arguments>
    write_file - The file to be written to.  This should be an already opened
                 file handle that was opened with write access.

    blocksize - The amount of data in bytes to write before a flush is performed.
    
    totalbytes - The total number of bytes that should be written for the test.

    use_sync - Set to True if sync should be used to make sure the data is
               actually written to disk.  Should not be set to True on
               Windows because sync does not exist there.  Defaults to False.

  <Side Effects>
    Creates a file of size totalbytes.

  <Exceptions>
    Exceptions could be thrown if there is a problem opening/writing the file.
    
    ZeroDivisionError if the drive is to fast for the accuracy of the clock (for
    a fast drive in combination with a time that provided poor granularity.

  <Return>
    A tuple (rate, fn) where rate is the measured write rate, and fn is the 
    name of the file created.  It is up to the caller to ensure that this 
    file is deleted.  We do not delete it here because it will likely be 
    useful in doing the read rate measurments.
  """
  
  start_time = nonportable.getruntime()
 
  for trial in range(0, totalbytes, blocksize):
    write_file_obj.write(' ' * blocksize)
    #write_file_obj.flush()
    #if use_sync:
    #  # Only use sync if it is requested. See comment at import for explanation.
    #  libc.sync()

  write_file_obj.flush()
  end_time = nonportable.getruntime()

  return (totalbytes)/(end_time - start_time)
开发者ID:JakobKallin,项目名称:Seastorm-Preview,代码行数:49,代码来源:measuredisk.py

示例6: do_sleep

def do_sleep(seconds):
  # Using getruntime() in lieu of time.time() because we want elapsed time 
  # regardless of the oddities of NTP
  start = nonportable.getruntime()
  sleeptime = seconds

  # return no earlier than the finish time
  finish = start + seconds

  while sleeptime > 0.0:
    time.sleep(sleeptime)
    now = nonportable.getruntime()

    # If sleeptime > 0.0 then I woke up early...
    sleeptime = finish - now
开发者ID:Ashmita89,项目名称:repy_v1,代码行数:15,代码来源:misc.py

示例7: _update_resource_consumption_table

def _update_resource_consumption_table(resource, resource_allowed_dict, consumed_resource_dict):

  thetime = nonportable.getruntime()

  # I'm going to reduce all renewable resources by the appropriate amount given
  # the amount of elapsed time.

  elapsedtime = thetime - consumed_resource_dict['renewable_update_time'][resource]

  consumed_resource_dict['renewable_update_time'][resource] = thetime

  if elapsedtime < 0:
    # A negative number (likely a NTP reset).   Let's just ignore it.
    return

  # Remove the charge
  reduction = elapsedtime * resource_allowed_dict[resource]
    
  if reduction > consumed_resource_dict[resource]:

    # It would reduce it below zero (so put it at zero)
    consumed_resource_dict[resource] = 0.0
  else:

    # Subtract some for elapsed time...
    consumed_resource_dict[resource] = consumed_resource_dict[resource] - reduction
开发者ID:Ashmita89,项目名称:attic,代码行数:26,代码来源:nanny.py

示例8: should_start_waitable_thread

def should_start_waitable_thread(threadid, threadname):
  # first time!   Let's init!
  if threadid not in thread_starttime:
    thread_waittime[threadid] = minwaittime
    thread_starttime[threadid] = 0.0

  # If it has been started, and the elapsed time is too short, always return
  # False to say it shouldn't be restarted
  if thread_starttime[threadid] and nonportable.getruntime() - thread_starttime[threadid] < thread_waittime[threadid]:
    return False
    
  for thread in threading.enumerate():
    if threadname in str(thread):
      # running now.   If it's run for a reasonable time, let's reduce the 
      # wait time...
      if nonportable.getruntime() - thread_starttime[threadid] > reasonableruntime:
        thread_waittime[threadid] = max(minwaittime, thread_waittime[threadid]-decreaseamount)
      return False
  else:
    return True
开发者ID:Ashmita89,项目名称:attic,代码行数:20,代码来源:nmmain.py

示例9: measure_read

def measure_read(read_file_obj, blocksize):
  """
  <Purpose>
    Attempts to measure the disk read rate by reading blocksize bytes from a
    temp file, timing how long it took, and dividing blocksize by the time
    to get the read rate.  Note that at this time, read rate is far too fast
    because it reads what was just written.  It should be ok to just take the
    value given by the write test and use it for both read and write rate.

  <Arguments>
    read_file_obj - The file object that is to be read from for the read test.
                    This file object is not closed by this function.
    blocksize - The number of bytes that should be read to determine the
                read rate.

  <Side Effects>
    None

  <Exceptions>
    Exceptions could be thrown if there is a problem opening/reading the file.

    ZeroDivisionError if the drive is to fast for the accuracy of the clock (for
    a fast drive in combination with a time that provided poor granularity.
    
  <Return>
    A tuple (rate, blocksize) where rate is the measured read rate, and 
    blocksize is the number of bytes actually read.  It will be no more than
    what was actually asked for, but it could be less if the given file was 
    too short.  The read rate will have been calculated using the returned
    blocksize.
  """

  # Time how long it takes to read in blocksize.
  start_time = nonportable.getruntime()
  junk_data = read_file_obj.read(blocksize)
  end_time = nonportable.getruntime()

  blocksize = len(junk_data)

  return (blocksize/(end_time - start_time), blocksize)
开发者ID:SeattleTestbed,项目名称:resource,代码行数:40,代码来源:measuredisk.py

示例10: stopvessel

def stopvessel(vesselname,exitparams=(44, '')):
  if vesselname not in vesseldict:
    raise BadRequest, "No such vessel"

  # this is broken out to prevent a race between checking the status and 
  # reporting the error
  currentstatus = vesseldict[vesselname]['status'] 
  # It must be started for us to stop it...
  if currentstatus != 'Started':
    raise BadRequest("Cannot stop vessel with status '"+currentstatus+"'")
  
  # Armon: Create the stop file, using a .tmp extension
  fileo = open(vesseldict[vesselname]['stopfilename']+".tmp","w")
  
  # Write out the stop string, Format: EINT;EMESG
  fileo.write(str(exitparams[0]) + ";" + exitparams[1])
  
  # Close the object
  fileo.close()
  
  # Rename the tmp file to the actual stopfile, this should be detected by repy now
  os.rename(vesseldict[vesselname]['stopfilename']+".tmp", vesseldict[vesselname]['stopfilename'])

  starttime = nonportable.getruntime()

  # wait for up to 10 seconds for it to stop (else return an error)
  while nonportable.getruntime()-starttime < 10:
    if vesseldict[vesselname]['status'] != 'Started':
      break

    # sleep while busy waiting...
    time.sleep(.5)

  else:
    return "May not have stopped in a timely manner\nWarning"
  
  return vesseldict[vesselname]['status']+"\nSuccess"
开发者ID:JakobKallin,项目名称:Seastorm-Preview,代码行数:37,代码来源:nmAPI.py

示例11: sleep

def sleep(seconds):
  """
   <Purpose>
      Allow the current event to pause execution (similar to time.sleep()).
      This function will not return early for any reason

   <Arguments>
      seconds:
         The number of seconds to sleep.   This can be a floating point value

   <Exceptions>
      RepyArgumentException if seconds is not an int/long/float.

   <Side Effects>
      None.

   <Returns>
      None.
  """

  # Check seconds to ensure it is a valid type.
  if type(seconds) not in [long, float, int]:
    raise RepyArgumentError("Invalid type " + str(type(seconds)))

  # Using getruntime() in lieu of time.time() because we want elapsed time 
  # regardless of the oddities of NTP
  start = nonportable.getruntime()
  sleeptime = seconds

  # Return no earlier than the finish time
  finish = start + seconds

  while sleeptime > 0.0:
    time.sleep(sleeptime)

    # If sleeptime > 0.0 then I woke up early...
    sleeptime = finish - nonportable.getruntime()
开发者ID:CallMeSteve,项目名称:repy_v2,代码行数:37,代码来源:emultimer.py

示例12: calculate_sleeptimes

def calculate_sleeptimes():
  ''' 
  <Purpose>
      calculate amount of sleep time for each process
  ''' 
  global pid_list
  global process_cpu_info

  ## calculate ecalapsed time of the last "period"
  global last_runtime
  global cpu_limit

  this_runtime = nonportable.getruntime()
  # print "Debug - this_runtime: ", this_runtime
  # if this_runtime == 0.0:
  #   print "Debug - this_runtime == 0.0 "
  #   return

  elapsedtime = this_runtime - last_runtime
  # print "Debug - last_runtime: ", last_runtime
  # print "Debug - this_runtime: ", this_runtime
  # print "\n"
  # print "Debug1 - elapsedtime: ", elapsedtime

  if elapsedtime < 0.0:
    print "Error: elapsed time < 0" 

  last_runtime = this_runtime


  for pid in pid_list:
    last_user_time = process_cpu_info[pid][0]
    if ostype == 'Windows':
      this_user_time = windows_api.get_process_cpu_time(pid)
    elif ostype == 'Linux':
      this_user_time = linux_api.get_process_cpu_time(pid)
    else:
      raise UnsupportedSystemException, "Unsupported system type: '"+osrealtype+"' (alias: "+ostype+")"
    # percent used is the amount of change divided by the time...
    percentused = (this_user_time - last_user_time) / elapsedtime 
    # print "Debug1 - pid:",pid, "percentused: ",percentused
    # Calculate amount of time to sleep for
    # print "Debug - cpu_limit: ",cpu_limit[pid]
    sleeptime = nanny.calculate_cpu_sleep_interval(cpu_limit[pid], percentused,elapsedtime)
    # print "Debug1 - pid:",pid,"sleeptime: ",sleeptime
    process_cpu_info[pid][1] = sleeptime
    process_cpu_info[pid][0] = this_user_time
开发者ID:taol,项目名称:crepy,代码行数:47,代码来源:crepy.py

示例13: getruntime

def getruntime():
  """
   <Purpose>
      Return the amount of time the program has been running.   This is in
      wall clock time. This is guaranteed to be monotonic.

   <Arguments>
      None

   <Exceptions>
      None.

   <Side Effects>
      None

   <Returns>
      The elapsed time as float
  """
  return nonportable.getruntime()
开发者ID:CallMeSteve,项目名称:repy_v2,代码行数:19,代码来源:emulmisc.py

示例14: getruntime

def getruntime():
  """
   <Purpose>
      Return the amount of time the program has been running.   This is in
      wall clock time.   This function is not guaranteed to always return
      increasing values due to NTP, etc.

   <Arguments>
      None

   <Exceptions>
      None.

   <Side Effects>
      None

   <Remarks>
      Accurate granularity not guaranteed past 1 second.

   <Returns>
      The elapsed time as float
  """
  restrictions.assertisallowed('getruntime')
  return nonportable.getruntime()
开发者ID:Ashmita89,项目名称:repy_v1,代码行数:24,代码来源:emulmisc.py

示例15: start_advert_thread

  start_advert_thread(vesseldict, myname, configuration['publickey'])

  # Start status thread...
  start_status_thread(vesseldict,configuration['pollfrequency'])


  # we should be all set up now.   

  servicelogger.log("[INFO]:Started")

  # I will count my iterations through the loop so that I can log a message
  # periodically.   This makes it clear I am alive.
  times_through_the_loop = 0

  # Setup the initial time for checking Affix status.
  last_check_affix_time = nonportable.getruntime()


  # BUG: Need to exit all when we're being upgraded
  while True:

    # E.K Previous there was a check to ensure that the accepter
    # thread was started.  There is no way to actually check this
    # and this code was never executed, so i removed it completely

    myname = node_reset_config['name']
        
    if not is_worker_thread_started():
      servicelogger.log("[WARN]:At " + str(time.time()) + " restarting worker...")
      start_worker_thread(configuration['pollfrequency'])
开发者ID:JakobKallin,项目名称:Seastorm-Preview,代码行数:30,代码来源:nmmain.py


注:本文中的nonportable.getruntime函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。