某些任务的响应时间正在减少

时间:2018-12-01 16:31:17

标签: python

我编写了一个代码,该代码应该可以接收一些图像并使它们成为黑白图像。我正在测量每个任务的响应时间(响应时间=接收每个图像并将其变为黑白的时间)。这是代码:

from __future__ import print_function
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
from select import select
import socket
from struct import pack
from struct import unpack
#from collections import deque
import commands
from PIL import Image
import time

host = commands.getoutput("hostname -I")
port = 5005
backlog = 5
BUFSIZE = 4096
queueList = []
start = []
end = []
temp = []

def processP(q):
    i = 0
    while q:
        name = q.pop(0)
        col = Image.open(name)
        gray = col.convert('L')
        bw = gray.point(lambda x: 0 if x<128 else 255, '1')
        bw.save("%d+30.jpg" % (i+1))
        end.append(time.time())
        #print(temp)
        i = i + 1


class Receiver:
    ''' Buffer binary data from socket conn '''
    def __init__(self, conn):
        self.conn = conn
        self.buff = bytearray()

    def get(self, size):
        ''' Get size bytes from the buffer, reading
            from conn when necessary 
        '''
        while len(self.buff) < size:
            data = self.conn.recv(BUFSIZE)
            if not data:
                break
            self.buff.extend(data)
        # Extract the desired bytes
        result = self.buff[:size]
        # and remove them from the buffer
        del self.buff[:size]
        return bytes(result)

    def save(self, fname):
        ''' Save the remaining bytes to file fname '''
        with open(fname, 'wb') as f:
            if self.buff:
                f.write(bytes(self.buff))
            while True:
                data = self.conn.recv(BUFSIZE)
                if not data:
                    break
                f.write(data)

def read_tcp(s):
    conn, addr = s.accept()
    print('Connected with', *addr)
    # Create a buffer for this connection
    receiver = Receiver(conn)
    # Get the length of the file name
    name_size = unpack('B', receiver.get(1))[0]
    name = receiver.get(name_size).decode()
    # Save the file
    receiver.save(name)
    conn.close()
    print('saved\n')
    queueList.append(name)
    print('name', name)
    start.append(time.time())
    if (name == "sample.jpg"):
        print('------------ok-------------')
        processP(queueList)
        print("Start: ", start)
        print('--------------------------')
        print("End: ", end)
        while start:
            temp.append(end.pop(0) - start.pop(0))
        print('****************************')
        print("Start: ", start)
        print('--------------------------')
        print("End: ", end)
        print("Temp: ", temp)
        i = 0
        while i < len(temp)-1:
            if (temp[i]<temp[i+1]):
                print('yes')
            else:
                print('No')
            i = i + 1

def read_udp(s):
    data,addr = s.recvfrom(1024)
    print("received message:", data)

def run():

    # create tcp socket
    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        tcp.bind((host,port))
    except socket.error as err:
        print('Bind failed', err)
        return
    tcp.listen(1)

    # create udp socket
    udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
    udp.bind((host,port))

    print('***Socket now listening at***:', host, port)
    input = [tcp,udp]

    try:
        while True:
            inputready,outputready,exceptready = select(input,[],[])

            for s in inputready:
                if s == tcp:
                    read_tcp(s)
                elif s == udp:
                    read_udp(s)
                else:
                    print("unknown socket:", s)

    # Hit Break / Ctrl-C to exit
    except KeyboardInterrupt:
        print('\nClosing')
        raise

    tcp.close()
    udp.close()

if __name__ == '__main__':
    run()

现在出于某些评估目的,我多次发送单个图像。当我查看响应时间时,我发现有时第8张图像的响应时间比第9张图像的响应时间长。

所以我的问题是,由于处理每个图像所需的大小和时间是相同的(我多次发送单个图像),为什么每个图像的响应时间是可变的?下一张图片的响应时间是否应该比上一张图片的响应时间更长(或至少等于)(例如,第四张图片的响应时间>第三张图片的响应时间)?

1 个答案:

答案 0 :(得分:0)

您的列表包含每个图像处理调用所花费的实际时间。该值将受很多因素影响,包括当时系统上的负载量。

在您的程序运行时,它不具有对其运行系统的所有资源(cpu,ram,磁盘)的独占访问权。操作系统争夺资源可能会管理数十,数百或数千个其他进程。鉴于此,当您以亚秒级的精度进行测量时,您极不可能看到在两次运行之间在精确相同的时间内处理过的同一幅图像。每次连续调用所花费的时间可以(也将)增加或减少。