Beispiel #1
0
def findAvgs(npEmpArr):
    import time 
    st=time.process_time_ns()
    avg,height=np.average(npEmpArr['age']),np.average(npEmpArr['age'])
    et=time.process_time_ns()
    print("Numpy time:{}".format(et-st))
    return et-st
Beispiel #2
0
 def helper(data):
     """
     if self.lang=="python":
         tracemalloc.start()
         start = time.process_time_ns()
         self.func(*data)
         current, peak = tracemalloc.get_traced_memory()
         end = time.process_time_ns()
         tracemalloc.stop()
         return end-start, peak
     else:
         params=param_gen.signature(self.func)
         l=[] #list of parameters
         for k in params:
             config=params[k].annotation
             l.append(config)
         return cpp_executor.execute(self.func_str,self.func.__name__,l,data)
     """
     tracemalloc.start()
     start = time.process_time_ns()
     self.func(*data)
     current, peak = tracemalloc.get_traced_memory()
     end = time.process_time_ns()
     tracemalloc.stop()
     return end - start, peak
Beispiel #3
0
    def readInt(self, regName):
        """
        reads a single register in the Trinamic chip. Records the status in self.status
        
        Note: if you want to read multiple registers, use readWriteMultiple.

        regName: Either the name of a register present in the register definition dictionary or an integer in the range 0 - 127
        
        returns the integer value of the register.
        """
        if self.SPIlog:
            cstart=time.perf_counter_ns()
            cpustart=time.process_time_ns()
        regint, regdef = self._checkRegName(regName, 'R')
        ba = bytes([regint
            , 0, 0, 0, 0])
        self.pigp.spi_write(self.spidev, ba)
        bblen, bytesback = self.pigp.spi_xfer(self.spidev, ba)
        if self.SPIrawlog:
            self.SPIrawlog.debug('SPI_WRITE: ' + ':'.join("{:02x}".format(c) for c in ba))
            self.SPIrawlog.debug('SPI_XFER : ' + ':'.join("{:02x}".format(c) for c in ba) + ' returned ' + ':'.join("{:02x}".format(c) for c in bytesback))
        assert bblen==5
        if 'readconv' in regdef:
            resint=regdef['readconv'](bytesback)
        else:
            resint=(bytesback[1]<<24)+(bytesback[2]<<16)+(bytesback[3]<<8)+bytesback[4]
        self.status=bytesback[0]
        if self.SPIlog:
            clockns=time.perf_counter_ns()-cstart
            cpuratio=(time.process_time_ns()-cpustart)/clockns*100
            self.SPIlog.log(self.loglvl," READ  {regname:10s}: {resint:9d} ({resint:08x}) status: {stat:02x} {clockus:6.1f}uS {cpu:4.1f}%CPU".format(
                    stat=bytesback[0], regname=str(regName),  clockus=clockns/1000, cpu=cpuratio))
        return resint
def doubling_flow_values_const_node_edges(nodes, edges, min_cap, max_cap,
                                          iterations):
    tab_array = []
    for i in range(iterations):
        array_graph = flow_utilities.generate_flow_network_given_links(
            nodes, edges, min_cap, max_cap)
        graph = FlowNetwork.Graph(array_graph)
        source = 0
        sink = nodes - 1
        start_time = time.process_time_ns()
        res = graph.FordFulkerson(source, sink)
        time_elapsed = time.process_time_ns() - start_time
        time_elapsed = time_elapsed / (10**6)
        if (time_elapsed != 0 and i > 0):
            if (tab_array[i - 1][3] != 0):
                ratio = time_elapsed / tab_array[i - 1][3]
                lg_ratio = math.log2(ratio)
        else:
            ratio = "-"
            lg_ratio = "-"
        tab_array.append([nodes, edges, res[0], time_elapsed, ratio, lg_ratio])
        min_cap = min_cap * 20
        max_cap = max_cap * 20
    print(
        tabulate(
            tab_array,
            ["Nodes", "edges", "max flow", " time(ms)", "ratio", "log2 ratio"],
            tablefmt="plain"))
def analyse_multiple_datasets(num_datasets):
    tab_array = []
    result_array = []
    edges_array = []
    for i in range(num_datasets):
        f = open("dataset-" + str(i), "r")
        num_links = f.readline()
        enc_flow_array = f.readline()
        flow_network = json.loads(enc_flow_array)
        f.close()

        flow_network_graph = FlowNetwork.Graph(flow_network)
        start_time = time.process_time_ns()
        result = flow_network_graph.FordFulkerson(0, len(flow_network) - 1)
        time_elapsed = time.process_time_ns() - start_time
        time_elapsed_ms = time_elapsed / (10**6)
        edges_array.append(int(num_links))
        result_array.append(time_elapsed_ms)
        if (time_elapsed != 0):
            if (tab_array[i - 1][3] != 0):
                ratio = time_elapsed / tab_array[i - 1][3]
        else:
            ratio = "-"
        tab_array.append(("dataset-" + str(i), num_links, result[0],
                          time_elapsed_ms, ratio))
    plt.plot(edges_array, result_array)
    plt.show()
    print(
        tabulate(tab_array,
                 ["dataset ", "edges", "max flow", "time taken(ms)", "ratio"],
                 tablefmt="plain"))
Beispiel #6
0
def get_pred(classifier, text, length, batch_size=100,
             sent_dict={"LABEL_0":-1, "LABEL_1":0, "LABEL_2":1}):
    
    res = np.zeros((length,2))
    cur_row = 0
    loading = 0

    t_start = time.process_time_ns()
    print(f"Row: {cur_row}. Progress: {loading}/100")
    for row in range(0,length,batch_size):
        output = classifier(list(text[row:min(length,row+batch_size)]))
        for i,elem in enumerate(output):
            senti = sent_dict[elem["label"]]
            score = elem["score"]

            cur_row = row + i
            res[cur_row] = [senti, score]

        if round(cur_row/length*100,0) > loading:

            loading = round(cur_row/length*100,0)
            t_stop = time.process_time_ns()
            elapsed_time = t_stop - t_start
            time_left = ((100-loading) * elapsed_time)*1e-9
            mins = round(time_left/60, 0)
            secs = round(time_left%60, 0)

            
            print(f"Row: {cur_row}. Progress: {loading}/100. \
                Time left: {mins} mins {secs} secs")

            t_start = time.process_time_ns()

    print("Processing complete!")
    return res
Beispiel #7
0
def simulate(algName, algPath, funcname, funcpath, heuris_args, initpoint):
    # loading the heuristic object into the namespace and memory
    spec = importlib.util.spec_from_file_location(algName, algPath)
    heuristic = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(heuristic)

    # loading the test function object into the namespace and memory
    testspec = importlib.util.spec_from_file_location(funcname, funcpath)
    func = importlib.util.module_from_spec(testspec)
    testspec.loader.exec_module(func)

    # defining a countable test function
    @counter
    def testfunc(args):
        return func.main(args)

    # using a try statement to handle potential exceptions raised by child processes like the algorithm or test functions or the pooling algorithm
    try:
        #This timer calculates directly the CPU time of the process (Nanoseconds)
        tic = time.process_time_ns()
        # running the test by calling the heuritic script with the test function as argument
        quality = heuristic.main(testfunc, initpoint, heuris_args)
        toc = time.process_time_ns()
        # ^^ The timer ends right above this; the CPU time is then calculated below by simple difference ^^

        # CPU time in seconds
        cpuTime = (toc - tic) * (10**-9)
        numCalls = testfunc.count
        converged = 1
    except:
        quality = NaN
        cpuTime = NaN
        numCalls = testfunc.count
        converged = 0
    return cpuTime, quality, numCalls, converged
Beispiel #8
0
    def on_post(self, req, resp):
        """Handles POST requests"""
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', '*')
        resp.set_header('Access-Control-Allow-Headers', '*')
        resp.set_header('Access-Control-Allow-Credentials', 'true')
        resp.set_header("Cache-Control", "no-cache")
        start = time.process_time_ns()
        # input_file = req.get_param('file')
        # if input_file.filename:
        #     bin = input_file.file.read()
        #     print(bin)

        data = req.stream.read(req.content_length)
        filename = "data/{}.png".format(time.time())
        open(filename, 'wb').write(data)
        img = cv2.imread(filename)
        print(img)

        # jsondata = json.loads(data)
        # clean_title = shortenlines(jsondata['1'])
        # clean_content = cleanall(jsondata['2'])
        # resp.media = self.bert_classification(clean_title, clean_content)

        logger.info("tot:{}ns".format(time.process_time_ns() - start))
        logger.info("###")
def trial_division_improved(n):
    t = time.process_time_ns()

    p_list = []

    it_count = 0

    while (n % 2 == 0):
        p_list.append(2)
        n /= 2

        it_count += 1

    p = Decimal(3)

    while (p * p <= n):
        while (n % p == 0):
            p_list.append(p)
            n /= p

        p += 2

        it_count += 1

    if (n != 1):
        p_list.append(n)

    if (len(p_list) > 2):
        print("AAAAAA")

    return int(p_list[0]), int(p_list[1]), it_count, time.process_time_ns() - t
Beispiel #10
0
def nn_model(trainx, trainy, valx, valy, bt_size, epochs, layers):
    model = Sequential()
    model.add(
        Dense(layers[0], activation='relu', input_shape=(trainx.shape[1], )))
    for l in layers[1:]:
        model.add(Dense(l, activation='relu'))
        model.add(Dropout(0.30))
    model.add(Dense(1, activation='sigmoid'))
    model.compile(optimizer='adam',
                  loss='binary_crossentropy',
                  metrics=['accuracy', f1_m, precision_m, recall_m])
    #model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

    hist = model.fit(trainx,
                     trainy,
                     batch_size=bt_size,
                     epochs=epochs,
                     shuffle=True,
                     validation_data=(valx, valy),
                     verbose=True)
    model.save('dnn.h5')
    loss, accuracy, f1_score, precision, recall = model.evaluate(valx,
                                                                 valy,
                                                                 verbose=0)
    start = time.process_time_ns()
    res = model.predict(valx)
    print("model evaluation time in clock",
          (time.process_time_ns() - start) / valx.shape[0], "ns for ",
          valx.shape[0], valx.shape[1], "test data in average")
    print("loss", loss, "accuracy", accuracy * 100, "f1_score", f1_score,
          "precision", precision, "recall", recall)
    return hist
Beispiel #11
0
def main() -> int:
    args = parser.parse_args()
    if args.mode == 'auto':
        args.mode = 'run'
    source = args.script.read()
    try:
        filename = args.script.name
    except Exception:
        filename = '<unknown>'
    tree = parse(source, filename)
    if args.mode == 'dump':
        print(ast.dump(tree, indent=3, include_attributes=True))
    elif args.mode == 'run':
        compiled = compile(tree, filename, 'exec')
        _run_code(compiled, {
            '__builtins__': builtins
        }, mod_name='__main__', script_name=filename)
    elif args.mode == 'py':
        print(ast.unparse(tree))
    elif args.mode == 'compile_only':
        error: None
        start = time.process_time_ns()
        try:
            compile(tree, filename, 'exec')
        except SyntaxError as e:
            error = e
        end = time.process_time_ns()
        if error is None:
            print(f'Successfully compiled "{filename}" (AST had {count_nodes(tree)} nodes) in {end - start}ns.')
        else:
            print(f'Failed to compile "{filename}" (AST had {count_nodes(tree)} nodes) in {end - start}ns.')
            import traceback
            traceback.print_exception(SyntaxError, error, error.__traceback__, 0)
            return 1
Beispiel #12
0
def test(state, kindOfTime:str):
    if kindOfTime == "p":
        start = time.process_time_ns()
    elif kindOfTime == "r":
        start = time.time()
    else:
        raise Exception("Wrong Format")
        
    threads = [ChangerThread(state) for i in range(1,18)]
    for t in threads:
        t.start()

    for t in threads:
        t.join()

    took =0

    if kindOfTime == "p":
        took = (time.process_time_ns() - start)/1000000

    elif kindOfTime == "r":
        took = (time.time() - start)/1000000
    else:
        raise Exception("Wrong Format")

    return took
Beispiel #13
0
    def revisions(self, path: Union[str, os.PathLike]) -> int:
        """Count revisions of a file

        This function can also take deleted paths into account while _find returns only undeleted paths.

        :returns: number of revisions
        :throws: DecentFsFileNotFound if not found
        """

        logging.debug('Searching for %s', path)
        revisions = 0
        seq = 0
        timer = time.process_time_ns()
        for entry in self.metafeed:
            # skip special block
            if seq == 0:
                seq += 1
                continue
            findpath, flags, timestamp, size, _ = cbor2.loads(entry.content())
            if findpath == path.__str__():
                timer = time.process_time_ns() - timer
                logging.info('Found with flags %s from %i with %i bytes',
                             flags, timestamp, size)
                logging.debug('Found at %i within %i ms', seq, timer / 1000000)
                revisions += 1
            seq += 1
        if revisions == 0:
            raise DecentFsFileNotFound('File {} not found'.format(
                path.__str__()))
        return revisions
Beispiel #14
0
    def _glob(self, glob: Union[str, os.PathLike]) -> list:
        """List files matich a glob pattern

        :returns: list of matching paths
        :throws: DecentFsFileNotFound if not found
        """

        logging.debug('Searching for %s', glob)
        seq = 0
        timer = time.process_time_ns()
        matchs = set()
        for entry in self.metafeed:
            # skip special block
            if seq == 0:
                seq += 1
                continue
            findpath, flags, _, _, _ = cbor2.loads(entry.content())
            logging.debug('Found %s with flags %s', findpath, flags)
            if pathlib.PurePosixPath(findpath).match(glob.__str__()):
                timer = time.process_time_ns() - timer
                logging.debug('Got a match at %i with flags %s within %i ms',
                              seq, flags, timer / 1000000)
                if flags == 'R':
                    matchs.remove(findpath)
                else:
                    matchs.add(findpath)
            seq += 1
        if len(matchs) == 0:
            raise DecentFsFileNotFound('File {} not found'.format(
                glob.__str__()))
        return matchs
Beispiel #15
0
def test_filereader_book1xlsx():
    path = Path(__file__).parent / "data" / 'book1.xlsx'
    assert path.exists()
    start = process_time_ns()
    tables = list(file_reader(path))
    end = process_time_ns()

    fields = sum(len(t) * len(t.columns) for t in tables)
    print("{:,} fields/seccond".format(
        round(1e9 * fields / max(1, end - start), 0)))

    sheet1 = Table(filename=path.name, sheet_name='Sheet1')
    for column_name in list('abcdef'):
        sheet1.add_column(column_name, int, False)

    sheet2 = Table(
        filename=path.name,
        sheet_name='Sheet2 ')  # there's a deliberate white space at the end!
    sheet2.add_column('a', int, False)
    for column_name in list('bcdef'):
        sheet2.add_column(column_name, float, False)

    books = [sheet1, sheet2]

    for book, table in zip(books, tables):
        table.show(slice(5))
        assert table.compare(book)
        assert len(table) == 45, len(table)
Beispiel #16
0
 def _updater(self):
     last_update = None
     try:
         updates = methods.get_updates(self.token, self.offset, 120)
         for update in updates:
             last_update = update
             t = time.process_time_ns()
             self._update_elaborator(update)
             elapsed_time = (time.process_time_ns() - t) / 1_000_000
             if elapsed_time > 50:
                 log.w(f"Update #{update['update_id']} elaboration "
                       f"took {elapsed_time} ms")
         last_update = None
     except Unauthorized:
         log.e(f"Unauthorized bot {self.bot_id}, detaching...")
         lotus_interface.detach_bot(self.token)
     except Conflict:
         log.e(
             f"Telegram said that bot {self.bot_id} is already running, detaching..."
         )
         lotus_interface.detach_bot(self.token)
     except requests.ConnectionError:
         log.e(
             f"A connection error happened, waiting {_connection_retry_time} seconds before reconnecting"
         )
         time.sleep(_connection_retry_time)
     except BadRequest as e:
         log.w(f"Warning, telegram said: {e.message}")
     except Exception as e:
         log.e('Error on line {}'.format(sys.exc_info()[-1].tb_lineno),
               type(e).__name__, e)
         traceback.print_tb(e.__traceback__)
         if last_update:
             pprint(last_update)
Beispiel #17
0
    def readInt(self, regName):
        """
        immediately reads a single register in the Trinamic chip. Records the status in SHORTSTAT register
        
        Note: if you want to read multiple registers, use readWriteMultiple.

        regName: Either the name of a register present in the register definition dictionary or an integer in the range 0 - 127
        
        returns the integer value of the register.
        """
        if self.SPIlog:
            cstart=time.perf_counter_ns()
            cpustart=time.process_time_ns()
        ba=[0]*5
        rrr=self['chipregs/'+regName]
        rrr.readBytes(ba)
        self.pigp.spi_write(self.spidev, ba)
        bblen, bytesback = self.pigp.spi_xfer(self.spidev, ba)
        assert bblen==5
        if self.SPIrawlog:
            self.SPIrawlog.debug('SPI_WRITE: ' + ':'.join("{:02x}".format(c) for c in ba))
            self.SPIrawlog.debug('SPI_XFER : ' + ':'.join("{:02x}".format(c) for c in ba) + ' returned ' + ':'.join("{:02x}".format(c) for c in bytesback))
        rrr.loadBytes(bytesback)
        resint=rrr.curval
        self['chipregs/SHORTSTAT'].loadByte(bytesback[0])
        if self.SPIlog:
            clockns=time.perf_counter_ns()-cstart
            cpuratio=(time.process_time_ns()-cpustart)/clockns*100
            self.SPIlog.log(self.loglvl," READ  {regname:10s}: {resint:9d} ({resint:08x}) status: {stat:02x} {clockus:6.1f}uS {cpu:4.1f}%CPU".format(
                    stat=bytesback[0], regname=str(regName),  resint=resint, clockus=clockns/1000, cpu=cpuratio))
        return resint
Beispiel #18
0
def run_timed_test(test, counter, loop_count = 1, maximum_time = -1.0):
    Logs.debug("\trunning test", test.__name__)
    counter.total += 1    
    timed = True
    try:
        start_time = time.process_time_ns()
    except AttributeError:
        Logs.debug("No timer module. Defaulting to untimed test")
        timed = False
        maximum_time = -1
    try:
        if (timed):
            for _ in range(loop_count):
                test()
            result_time = (time.process_time_ns() - start_time) / 1000000000.0
            Logs.debug("\texecuted in", result_time, "seconds.", result_time/loop_count, "seconds per test.", "Reference time:", maximum_time, "seconds")
        else:
            test()
    except Exception as e:
        Logs.error("\ttest failed.")
        Logs.error(e)
    else:
        if maximum_time >= 0.0 and result_time > maximum_time:
            Logs.error("\ttest successful but too slow")
        else:
            counter.passed += 1
Beispiel #19
0
 def writeInt(self, regName, regValue):
     """
     Writes to a single register in the Trinamic chip
     
     regName: Either the name of a register present in the register definition dictionary or an integer in the range 0 - 127
     
     regValue: a value interpreted as a simple 32 bit integer that will be written to the chip.
     """
     if self.SPIlog:
         cstart=time.perf_counter_ns()
         cpustart=time.process_time_ns()
     regint, _ = self._checkRegName(regName, 'W')
     valueint=regValue
     ba = bytes([regint|128
         , (valueint>>24) & 255
         , (valueint>>16) & 255
         , (valueint>>8) & 255
         , valueint & 255])
     self.pigp.spi_write(self.spidev, ba)
     self.lastwritten[regName]=regValue
     if self.SPIrawlog:
         self.SPIrawlog.debug('SPI_WRITE: ' + ':'.join("{:02x}".format(c) for c in ba))
     if self.SPIlog:
         clockns=time.perf_counter_ns()-cstart
         cpuratio=(time.process_time_ns()-cpustart)/clockns*100
         self.SPIlog.debug("WRITE" + " {regname:10s}: {regval:9d} ({regval:08x}) {clockus:6.1f}uS {cpu:4.1f}%CPU".format(
                 regname=str(regName), regval=valueint, clockus=clockns/1000, cpu=cpuratio,))
def test_model(train_set,
               test_set,
               model,
               filename=None,
               prefix="test",
               epochs=300):
    """:key
    """
    training = model.build_slice_set(train_set)
    print("debug - start training " + prefix)
    tmr = time.process_time_ns()
    model.train(training, training, epochs)
    train_time = time.process_time_ns() - tmr
    print("debug - start testing")
    true_map = LTMap.LiteTuxMap(1, 1)
    for lvlfile in test_set:
        s = prefix + "," + str(train_time) + "," + lvlfile + "," + str(
            epochs) + ","
        lvl_chunks = model.build_slice_set([lvlfile], True)
        true_map.load(lvlfile)
        predicted_map = LTMap.LiteTuxMap(true_map.width, true_map.height)
        for i in range(lvl_chunks.shape[0]):
            slc = model.predict(lvl_chunks[i])
            model.decode_slice(slc[0], predicted_map, i * model.cols)
        print(predicted_map.to_vertical_string())
        test = MapTest(true_map, predicted_map)
        s += str(test.get_total_tile_errors()) + ","
        s += str(test.get_average_tile_hamming_error()) + ","
        s += str(test.get_average_distance_error()) + ","

        print(s)
        if filename is not None:
            with open(filename, "a") as f:
                f.write(s)
                f.write("\n")
Beispiel #21
0
def time_execution(DATASET):

    # pro asserty
    time1 = []
    time2 = []

    for _ in range(0, 4):
        start_time1 = time.process_time_ns()
        tree1 = alternative_kruskal(load_dataset(DATASET))
        time1.append(time.process_time_ns() - start_time1)
        start_time2 = time.process_time_ns()
        tree2 = og_kruskal(load_dataset(DATASET))
        time2.append(time.process_time_ns() - start_time2)

    print("Asserting minimum spanning trees...")
    assert (len(tree1) == len(tree2))
    assert (count_minimum_spanning_tree_weight(tree1) ==
            count_minimum_spanning_tree_weight(tree2))
    assert (find_vertices_in_tree(tree1) == find_vertices_in_tree(tree2))
    print("Assert passed. Executing...\n")

    print("Time of execution of my kruskal implementation on the dataset '{}'".
          format(DATASET))
    print(str((sum(time1) / len(time1)) / 1000000000.0) + " s")

    print(
        "-----------------------------------------------------------------------"
    )

    print("Timing of the original kruskal implementation on the dataset {}".
          format(DATASET))
    print(str((sum(time2) / len(time2)) / 1000000000.0) + " s")
    print("\n")
Beispiel #22
0
def execute_this(code_to_execute):
    # I was tired of importing time and then making a start variable, calling the execution time function, I just wrote this
    clear_output_screen()
    print(f"Running {code_to_execute.__name__}\n")
    start = process_time_ns()
    code_to_execute()
    execution_time(process_time_ns()-start)
Beispiel #23
0
def measure_time(strings: list) -> float:
    print("measuring")
    start = time.process_time_ns()
    for num in strings:
        hashlib.sha1(num.encode()).hexdigest()
    end = time.process_time_ns() - start
    return end
Beispiel #24
0
def test_model(data_size, model_name, outfile, mode):
    print("Testing model ")
    f = open(outfile, mode)
    outstring = ""
    model = load_model(model_name)
    data_test = generate_data(data_size)
    outstring += "Count on {} | Count off {}  Percent on {} % \n".format(
        data_test["count_on"], data_test["count_off"], data_test["percent_on"])
    time_count = time.process_time_ns()
    t = model.predict(data_test["data"][0], verbose=0)
    time_count = time.process_time_ns() - time_count
    outstring += "Predict time {} = {}s\n".format(time_count,
                                                  time_count / 1000000000)
    count_miss = 0
    missed = []
    for i in range(len(t)):
        pred_val = 0 if t[i][0] < 0.5 else 1
        #print("{} {}".format(x_test[i],pred_val))
        if pred_val != data_test["data"][1][i]:
            count_miss = (count_miss + 1)
            missed.append([data_test["data"][0][i], pred_val])
            outstring += "Wrong {} true_val {} != {} predict\n".format(
                data_test["data"][0][i], data_test["data"][1][i], t[i])
    outstring += "Missed {} in {} = {}% \n".format(count_miss, len(t),
                                                   count_miss / len(t) * 100)
    f.write(outstring)
    f.close()
    print("Finished testing model ")
Beispiel #25
0
 def wrapper(*args, **kwargs):
     start = time.process_time_ns()
     result = func(*args, **kwargs)
     end = time.process_time_ns()
     print(
         f'{func.__qualname__}({args}, {kwargs}) Elapsed: {(end-start)/10**6} ms'
     )
     return result
Beispiel #26
0
def testIsSubsequence():
    start = process_time_ns()

    for test in tests:
        print(runTest(tests[test][0], tests[test][1], test))

    end = process_time_ns()
    print("Time elapsed:", end - start, "ns")
Beispiel #27
0
 def test_process_time_ns(self):
     import time
     t1 = time.process_time_ns()
     assert isinstance(t1, int)
     time.sleep(0.1)
     t2 = time.process_time_ns()
     # process_time_ns() should not include time spent during sleep
     assert (t2 - t1) < 5 * 10**7
     assert abs(time.process_time() - time.process_time_ns() * 1e-9) < 0.1
Beispiel #28
0
    def add_movies(self):
        index = 0

        for titles in self.movie_collection:
            if index == 0:  # Skips extraneous data in first entry.
                time.process_time_ns()
            else:
                self.movies.append(titles.text)
            index += 1
def test_compress_action(state, action, n_colors):
    state_len = len(state)
    power_list = [n_colors**i for i in range(state_len)]
    x = compress_state(state, n_colors)
    # print(decompress_state(x, n_colors, state_len))
    start = time.process_time_ns()
    x = perform_compressed_action(x, action, power_list, n_colors)
    end = time.process_time_ns()
    return decompress_state(x, n_colors, state_len), end - start
def testSortedSquareArray():
    start = process_time_ns()
    if (sortedSquaredArray([1, 2, 3, 5, 6, 8, 9]) == [1, 4, 9, 25, 36, 64,
                                                      81]):
        print(True)
    else:
        print(f"returned {sortedSquaredArray([1, 2, 3, 5, 6, 8, 9])}")
        print("expected [1, 4, 9, 25, 36, 64,81]")

    if (sortedSquaredArray([1]) == [1]):
        print(True)
    else:
        print(f"returned {sortedSquaredArray([1])}")
        print("expected [1]")

    if (sortedSquaredArray([1, 4]) == [1, 16]):
        print(True)
    else:
        print(f"returned {sortedSquaredArray([1, 4])}")
        print("expected [1, 16]")

    # if(sortedSquaredArray([1, 4]) == [1, 16]):
    #     print(True)
    # else:
    #     print(f"returned {sortedSquaredArray([1, 4])}")
    #     print("expected [1, 16]")

# print(sortedSquaredArray([1, 2, 3, 4, 5]))
# -> [1, 4, 9, 16, 25]
# print(sortedSquaredArray([0]))
# -> [0]
# print(sortedSquaredArray([100]))
# -> [100]
# print(sortedSquaredArray([-1]))
# -> [1]
# print(sortedSquaredArray([-1, -4]))
# -> [1, 4]
# print(sortedSquaredArray([-5, -4, -3, -2, -1]))
# -> [1, 4, 9, 16, 25]
# print(sortedSquaredArray([-10]))
# -> [100]
# print(sortedSquaredArray([-10, -5, 0, 5, 10]))
# -> [0, 25, 25, 100, 100]
# print(sortedSquaredArray([-7, -3, 1, 9, 22, 30]))
# -> [1, 9, 49, 81, 484, 900]
# print(sortedSquaredArray([-50, -13, -2, -1, 0, 0, 1, 1, 2, 3, 19, 20]))
# -> [0, 0, 1, 1, 1, 4, 4, 9, 169, 361, 400, 2500]
# print(sortedSquaredArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]))
# -> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# print(sortedSquaredArray([-1, -1, 2, 3, 3, 3, 4]))
# -> [1, 1, 4, 9, 9, 9, 16]
# print(sortedSquaredArray([-3, -2, -1]))
# -> [1, 4, 9]

    end = process_time_ns()
    print("Time elapsed:", end - start, "ns")
Beispiel #31
0
    def test_time_ns_type(self):
        def check_ns(sec, ns):
            self.assertIsInstance(ns, int)

            sec_ns = int(sec * 1e9)
            # tolerate a difference of 50 ms
            self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))

        check_ns(time.time(),
                 time.time_ns())
        check_ns(time.monotonic(),
                 time.monotonic_ns())
        check_ns(time.perf_counter(),
                 time.perf_counter_ns())
        check_ns(time.process_time(),
                 time.process_time_ns())

        if hasattr(time, 'clock_gettime'):
            check_ns(time.clock_gettime(time.CLOCK_REALTIME),
                     time.clock_gettime_ns(time.CLOCK_REALTIME))