Python time.process_time() Examples

The following are code examples for showing how to use time.process_time(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: zmirror   Author: aploium   File: zmirror.py    MIT License 6 votes vote down vote up
def generate_our_response():
    """
    生成我们的响应
    :rtype: Response
    """
    # copy and parse remote response
    resp = copy_response(is_streamed=parse.streamed_our_response)

    if parse.time["req_time_header"] >= 0.00001:
        parse.set_extra_resp_header('X-Header-Req-Time', "%.4f" % parse.time["req_time_header"])
    if parse.time.get("start_time") is not None and not parse.streamed_our_response:
        # remote request time should be excluded when calculating total time
        parse.set_extra_resp_header('X-Body-Req-Time', "%.4f" % parse.time["req_time_body"])
        parse.set_extra_resp_header('X-Compute-Time',
                                    "%.4f" % (process_time() - parse.time["start_time"]))

    parse.set_extra_resp_header('X-Powered-By', 'zmirror/%s' % CONSTS.__VERSION__)

    if developer_dump_all_traffics and not parse.streamed_our_response:
        dump_zmirror_snapshot("traffic")

    return resp 
Example 2
Project: zmirror   Author: aploium   File: test_regex.py    MIT License 6 votes vote down vote up
def performance_test__regex_basic_mirrorlization(self):
        """对 regex_basic_mirrorlization 进行性能测试"""
        from more_configs.config_google_and_zhwikipedia import target_domain, external_domains
        self.reload_zmirror(configs_dict=dict(
            target_domain=target_domain,
            external_domains=external_domains,
        ))
        from time import process_time
        reg_func = self.zmirror.response_text_basic_mirrorlization
        print(self.zmirror.regex_basic_mirrorlization.pattern)

        with open(zmirror_file("tests/sample/google_home.html"), "r", encoding="utf-8") as fp:
            text = fp.read()

        start_time = process_time()
        for _ in range(1000):
            reg_func(text)
        print("100x google_home.html", process_time() - start_time) 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: profile.py    GNU General Public License v3.0 6 votes vote down vote up
def trace_dispatch(self, frame, event, arg):
        timer = self.timer
        t = timer()
        t = t[0] + t[1] - self.t - self.bias

        if event == "c_call":
            self.c_func_name = arg.__name__

        if self.dispatch[event](self, frame,t):
            t = timer()
            self.t = t[0] + t[1]
        else:
            r = timer()
            self.t = r[0] + r[1] - t # put back unrecorded delta

    # Dispatch routine for best timer program (return = scalar, fastest if
    # an integer but float works too -- and time.process_time() relies on that). 
Example 4
Project: NiujiaoDebugger   Author: MrSrc   File: test_time.py    GNU General Public License v3.0 6 votes vote down vote up
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, 'thread_time'):
            check_ns(time.thread_time(),
                     time.thread_time_ns())

        if hasattr(time, 'clock_gettime'):
            check_ns(time.clock_gettime(time.CLOCK_REALTIME),
                     time.clock_gettime_ns(time.CLOCK_REALTIME)) 
Example 5
Project: NiujiaoDebugger   Author: MrSrc   File: test_time.py    GNU General Public License v3.0 6 votes vote down vote up
def test_get_clock_info(self):
        clocks = ['clock', 'monotonic', 'perf_counter', 'process_time', 'time']

        for name in clocks:
            if name == 'clock':
                with self.assertWarns(DeprecationWarning):
                    info = time.get_clock_info('clock')
            else:
                info = time.get_clock_info(name)

            #self.assertIsInstance(info, dict)
            self.assertIsInstance(info.implementation, str)
            self.assertNotEqual(info.implementation, '')
            self.assertIsInstance(info.monotonic, bool)
            self.assertIsInstance(info.resolution, float)
            # 0.0 < resolution <= 1.0
            self.assertGreater(info.resolution, 0.0)
            self.assertLessEqual(info.resolution, 1.0)
            self.assertIsInstance(info.adjustable, bool)

        self.assertRaises(ValueError, time.get_clock_info, 'xxx') 
Example 6
Project: vo_single_camera_sos   Author: ubuntuslave   File: camera_models.py    GNU General Public License v3.0 6 votes vote down vote up
def view_all_panoramas(self, omni_images_filename_pattern, img_indices, win_name_modifier = "", use_mask = False, mask_color_RGB = None):
        import warnings
        from omnistereo.common_cv import get_images

        omni_images = get_images(omni_images_filename_pattern, indices_list = img_indices, show_images = not use_mask)

        if img_indices is None or len(img_indices) == 0:  # Default value
            # use all the images in the set:
            img_indices = range(len(omni_images))

        for i in img_indices:
            try:
                #===============================================================
                # from time import process_time  # , perf_counter
                # start_time = process_time()
                #===============================================================
                self.generate_panorama(omni_images[i], idx = i, view = True, win_name_modifier = win_name_modifier, use_mask = use_mask, border_RGB_color = mask_color_RGB)
                #===============================================================
                # end_time = process_time()
                # time_ellapsed_1 = end_time - start_time
                # print("Time elapsed: {time:.8f} seconds".format(time=time_ellapsed_1))
                #===============================================================
            except:
                warnings.warn("Image index %d not found at %s" % (i, __name__)) 
Example 7
Project: eventsourcing   Author: johnbywater   File: runner.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self) -> None:
        while not self.stop_event.is_set():

            try:
                self.fetch_barrier.wait()
                self.execute_barrier.wait()
                self.execute_barrier.wait()
                self.call_commands()
            except BrokenBarrierError:
                self.fetch_barrier.abort()
                self.execute_barrier.abort()
                self.stop_event.set()
            else:
                tick_time = time.time()
                process_time = time.process_time()
                if self.last_tick_time:
                    self.do_tick(process_time, tick_time)

                self.last_tick_time = tick_time
                self.last_process_time = process_time
                self.tick_count += 1

                if self.tick_interval:
                    sleep_interval = self.tick_interval - self.tick_adjustment
                    sleep(max(sleep_interval, 0)) 
Example 8
Project: sqlmap-gtk   Author: needle-wang   File: sqlmap_gtk.py    GNU General Public License v3.0 6 votes vote down vote up
def main():
  import time

  start = time.process_time()
  # --------
  win = Window()

  css_provider = g.CssProvider.new()
  css_provider.load_from_path('css.css')
  g.StyleContext.add_provider_for_screen(
    d.Screen.get_default(),
    css_provider,
    g.STYLE_PROVIDER_PRIORITY_APPLICATION
  )

  win.connect('destroy', lambda x: win.on_window_destroy())
  # win.maximize()
  win.show_all()
  # --------
  end = time.process_time()
  print('loading cost: %s Seconds' % (end - start))
  g.main() 
Example 9
Project: pymhlib   Author: ac-tuwien   File: sa.py    GNU General Public License v3.0 6 votes vote down vote up
def sa(self, sol: Solution):
        """Perform simulated annealing with geometric cooling on given solution."""

        def sa_iteration(sol: Solution, _par, result):
            neighborhood_move, delta_obj = self.random_move_delta_eval(sol)
            acceptance = self.metropolis_criterion(sol, delta_obj)
            if acceptance:
                self.apply_neighborhood_move(sol, neighborhood_move)
                sol.obj_val = sol.obj_val + delta_obj
                result.changed = True
            if self.iter_cb is not None:
                self.iter_cb(self.iteration, sol, self.temperature, acceptance)
        sa_method = Method("sa", sa_iteration, 0)

        while True:
            for it_ in range(self.equi_iter):
                t_start = time.process_time()
                obj_old = self.incumbent.obj()
                res = self.perform_method(sa_method, sol, delayed_success=True)
                self.delayed_success_update(sa_method, obj_old, t_start, sol)
                if res.terminate:
                    return True
            self.cool_down() 
Example 10
Project: pymhlib   Author: ac-tuwien   File: scheduler.py    GNU General Public License v3.0 6 votes vote down vote up
def perform_method_pair(self, destroy: Method, repair: Method, sol: Solution) -> Result:
        """Performs a destroy/repair method pair on given solution and returns Results object.

        Also updates incumbent, iteration and the method's statistics in method_stats.
        Furthermore checks the termination condition and eventually sets terminate in the returned Results object.

        :param destroy: destroy destroy method to be performed
        :param repair: repair destroy method to be performed
        :param sol: solution to which the method is applied
        :returns: Results object
        """
        res = Result()
        obj_old = sol.obj()
        t_start = time.process_time()
        destroy.func(sol, destroy.par, res)
        t_destroyed = time.process_time()
        repair.func(sol, repair.par, res)
        t_end = time.process_time()
        self.update_stats_for_method_pair(destroy, repair, sol, res, obj_old,
                                          t_destroyed - t_start, t_end - t_destroyed)
        return res 
Example 11
Project: pymhlib   Author: ac-tuwien   File: gvns.py    GNU General Public License v3.0 6 votes vote down vote up
def gvns(self, sol: Solution):
        """Perform general variable neighborhood search (GVNS) to given solution."""
        sol2 = sol.copy()
        if self.vnd(sol2) or not self.meths_sh:
            return
        use_vnd = bool(self.meths_li)
        while True:
            for m in self.next_method(self.meths_sh, repeat=True):
                t_start = time.process_time()
                res = self.perform_method(m, sol2, delayed_success=use_vnd)
                terminate = res.terminate
                if not terminate and use_vnd:
                    terminate = self.vnd(sol2)
                self.delayed_success_update(m, sol.obj(), t_start, sol2)
                if sol2.is_better(sol):
                    sol.copy_from(sol2)
                    if terminate or res.terminate:
                        return
                    break
                else:
                    if terminate or res.terminate:
                        return
                    sol2.copy_from(sol)
            else:
                break 
Example 12
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_time.py    GNU General Public License v3.0 6 votes vote down vote up
def test_get_clock_info(self):
        clocks = ['clock', 'perf_counter', 'process_time', 'time']
        if hasattr(time, 'monotonic'):
            clocks.append('monotonic')

        for name in clocks:
            info = time.get_clock_info(name)
            #self.assertIsInstance(info, dict)
            self.assertIsInstance(info.implementation, str)
            self.assertNotEqual(info.implementation, '')
            self.assertIsInstance(info.monotonic, bool)
            self.assertIsInstance(info.resolution, float)
            # 0.0 < resolution <= 1.0
            self.assertGreater(info.resolution, 0.0)
            self.assertLessEqual(info.resolution, 1.0)
            self.assertIsInstance(info.adjustable, bool)

        self.assertRaises(ValueError, time.get_clock_info, 'xxx') 
Example 13
Project: openspectra   Author: openspectra   File: file_writer_test.py    Apache License 2.0 6 votes vote down vote up
def write_sub_cube_slice():
    test_file = "unit_tests/resources/cup95_eff_fixed"
    # test_file = "../resources/cup95_eff_fixed"
    os_file = OpenSpectraFileFactory.create_open_spectra_file(test_file)

    start_time = time.process_time()

    # TODO intent was cube would be zero based but slice treats the end param as position - 1
    # TODO although this is the python/numpy way so stick with it?
    sub_cube = os_file.cube((0, 350), (0, 400), (0, 50)).astype(np.int16)
    # print("sub-cube.shape: ", sub_cube.shape)
    # print("sub-cube: ", sub_cube)

    flat_iterator = sub_cube.flat
    with open("./resources/test_out_cube1", "wb") as out_file:
        for item in flat_iterator:
            out_file.write(item)

        out_file.flush()

    end_time = time.process_time()
    print("Total time with slice: {0}".format(end_time - start_time)) 
Example 14
Project: openspectra   Author: openspectra   File: file_writer_test.py    Apache License 2.0 6 votes vote down vote up
def write_sub_cube_list():
    test_file = "unit_tests/resources/cup95_eff_fixed"
    # test_file = "../resources/cup95_eff_fixed"
    os_file = OpenSpectraFileFactory.create_open_spectra_file(test_file)

    start_time = time.process_time()

    # TODO intent was cube would be zero based but slice treats the end param as position - 1
    # TODO although this is the python/numpy way so stick with it?
    bands = list(range(50))
    sub_cube = os_file.cube((0, 350), (0, 400), bands).astype(np.int16)
    # print("sub-cube.shape: ", sub_cube.shape)
    # print("sub-cube: ", sub_cube)

    flat_iterator = sub_cube.flat
    with open("./resources/test_out_cube2", "wb") as out_file:
        for item in flat_iterator:
            out_file.write(item)

        out_file.flush()

    end_time = time.process_time()
    print("Total time with list: {0}".format(end_time - start_time)) 
Example 15
Project: openspectra   Author: openspectra   File: file_reader_test.py    Apache License 2.0 6 votes vote down vote up
def loadTest3(self, file_name):
        if self.__open_file(file_name):
            print("Running test3...")

            start_time = time.process_time()
            # TODO so I'm still not sure if this is loading the whole file or just mappoing it
            file:np.memmap = np.memmap(self.__path, dtype=self.__data_type, mode='r', shape=(self.__lines, self.__bands, self.__samples))
            end_time = time.process_time()
            print("Loaded file size: {0}, shape: {1}, in {2} ms".format(file.size, file.shape, (end_time - start_time) * 1000))
            print("File size is: {0}".format(sys.getsizeof(file)))

            start_time = time.process_time()
            data = np.copy(file)
            end_time = time.process_time()
            print("Full array copied in: {0} ms".format((end_time - start_time) * 1000))
            print("File size is: {0}".format(sys.getsizeof(file)))
            print("Data size is: {0}".format(sys.getsizeof(data)))

            del file

            print("Copy of data size: {0}, shape: {1}".format(data.size, data.shape))
            print("Test3 complete...") 
Example 16
Project: ExAssist   Author: flyaway1217   File: assist.py    GNU General Public License v3.0 6 votes vote down vote up
def _start(self):
        if not self._locked:
            self._start_time = time.process_time()
            # Clear the state
            self._run = dict()
            self._current_info = collections.defaultdict(dict)
            self._info = []

            start_time = time.time()
            strtime = time.strftime(
                     '%Y-%m-%d %H:%M:%S', time.localtime(start_time))

            self._path = self._init_experiment()
            self._read_config()
            # replace the path in runpath section
            self._set_runpath_config(self._path)
            # write back the configurations
            self._write_config()
            self._locked = True

            self._run['host_info'] = self._get_host_info()
            self._run['start_time'] = strtime
            self._run['comments'] = self._comments 
Example 17
Project: ExAssist   Author: flyaway1217   File: assist.py    GNU General Public License v3.0 6 votes vote down vote up
def _end_time(self):
        # CPU time
        end_time = time.process_time()
        cpu_lapse = end_time - self._start_time
        strtime = timedelta(seconds=cpu_lapse)
        self._run['cpu_time'] = str(strtime)

        # Stop time
        end_time = time.time()
        strtime = time.strftime(
                 '%Y-%m-%d %H:%M:%S', time.localtime(end_time))
        self._run['stop_time'] = strtime

        # Lapse time
        start_time = time.strptime(self._run['start_time'],
                                   '%Y-%m-%d %H:%M:%S')
        start_time = time.mktime(start_time)
        time_lapse = end_time - start_time
        strtime = timedelta(seconds=time_lapse)
        self._run['lapse_time'] = str(strtime) 
Example 18
Project: pydebug   Author: benmezger   File: info.py    MIT License 6 votes vote down vote up
def debug_func(self, *args, **kwargs):
        perf_start = time.perf_counter()
        proc_start = time.process_time()

        ret = self.func(*args, **kwargs)

        total_perf = (time.perf_counter() - perf_start) / 60
        total_proc = (time.process_time() - proc_start) / 60

        name = self.func.__name__ if self.is_func else self.func.__class__.__name__
        if self.is_func:
            self.logger.debug(f"Calling {name}({self.signature})")
            self.logger.debug(f"{name!r} Elapsed time: {total_perf} [min]")
            self.logger.debug(f"{name!r} CPU process time: {total_proc} [min]")
            self.logger.debug(f"{name!r} returned {ret!r}")
        else:
            self.logger.debug(f"Calling {name}({self.signature})")
            self.logger.debug(f"{name!r} Elapsed time: {total_perf} [min]")
            self.logger.debug(f"{name!r} CPU process time: {total_proc} [min]")
            self.logger.debug(f"{name!r} returned {ret!r}")

        return ret 
Example 19
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: profile.py    GNU General Public License v2.0 6 votes vote down vote up
def trace_dispatch(self, frame, event, arg):
        timer = self.timer
        t = timer()
        t = t[0] + t[1] - self.t - self.bias

        if event == "c_call":
            self.c_func_name = arg.__name__

        if self.dispatch[event](self, frame,t):
            t = timer()
            self.t = t[0] + t[1]
        else:
            r = timer()
            self.t = r[0] + r[1] - t # put back unrecorded delta

    # Dispatch routine for best timer program (return = scalar, fastest if
    # an integer but float works too -- and time.process_time() relies on that). 
Example 20
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_time.py    GNU General Public License v2.0 6 votes vote down vote up
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, 'thread_time'):
            check_ns(time.thread_time(),
                     time.thread_time_ns())

        if hasattr(time, 'clock_gettime'):
            check_ns(time.clock_gettime(time.CLOCK_REALTIME),
                     time.clock_gettime_ns(time.CLOCK_REALTIME)) 
Example 21
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_time.py    GNU General Public License v2.0 6 votes vote down vote up
def test_get_clock_info(self):
        clocks = ['clock', 'monotonic', 'perf_counter', 'process_time', 'time']

        for name in clocks:
            if name == 'clock':
                with self.assertWarns(DeprecationWarning):
                    info = time.get_clock_info('clock')
            else:
                info = time.get_clock_info(name)

            #self.assertIsInstance(info, dict)
            self.assertIsInstance(info.implementation, str)
            self.assertNotEqual(info.implementation, '')
            self.assertIsInstance(info.monotonic, bool)
            self.assertIsInstance(info.resolution, float)
            # 0.0 < resolution <= 1.0
            self.assertGreater(info.resolution, 0.0)
            self.assertLessEqual(info.resolution, 1.0)
            self.assertIsInstance(info.adjustable, bool)

        self.assertRaises(ValueError, time.get_clock_info, 'xxx') 
Example 22
Project: thepipe   Author: tamasgal   File: core.py    MIT License 6 votes vote down vote up
def finish(self):
        """Call finish() on each attached module"""
        finish_blob = Blob()
        for module in self.modules:
            if hasattr(module, 'pre_finish'):
                self.log.info("Finishing %s" % module.name)
                start_time = timer()
                start_time_cpu = time.process_time()
                finish_blob[module.name] = module.pre_finish()
                self._timeit[module]['finish'] = timer() - start_time
                self._timeit[module]['finish_cpu'] = \
                    time.process_time() - start_time_cpu
            else:
                self.log.info("Skipping function module %s" % module.name)
        self._timeit['finish'] = timer()
        self._timeit['finish_cpu'] = time.process_time()
        self._print_timeit_statistics()
        self._finished = True

        return finish_blob 
Example 23
Project: FATE   Author: FederatedAI   File: metric_utils.py    Apache License 2.0 6 votes vote down vote up
def record_metrics(func):
    from functools import wraps

    @wraps(func)
    def wrapper(*args, **kw):
        try:
            start = time.process_time()
            result = func(*args, **kw)
            result_status = 'success'
        except Exception:
            result_status = 'error'
            raise
        finally:
            end = time.process_time()
            LOGGER.debug('{}.{}: {} status: {}'.format(func.__module__, func.__name__, end - start, result_status))
        return result

    return wrapper 
Example 24
Project: steamlink   Author: steamlink   File: steamlink.py    MIT License 5 votes vote down vote up
def start(self):
		process_time = time.process_time()
		now = time.time()
		delta = 0
		wait = 1
		logger.info("%s starting heartbeat", self.name)
		FLUSHWAIT = 10
		flushwait = FLUSHWAIT
		while True:
			await asyncio.sleep(wait)
			self.heartbeat()
			flushwait -= 1
			if flushwait == 0:
				_DB.flush()  # N.B. expensive
				flushwait = FLUSHWAIT

			n_process_time = time.process_time()
			n_now = time.time()

			delta = n_now - now
			wait = 1 - (n_now % 1)
			self.cpubusy = ((n_process_time - process_time) / delta) * 100.0
			now = n_now
			process_time = n_process_time
			#			if DBG == 0:	# N.B. reduce noise when debuging, i.e. no heartbeat
			self.update(True) 
Example 25
Project: NiujiaoDebugger   Author: MrSrc   File: profile.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, timer=None, bias=None):
        self.timings = {}
        self.cur = None
        self.cmd = ""
        self.c_func_name = ""

        if bias is None:
            bias = self.bias
        self.bias = bias     # Materialize in local dict for lookup speed.

        if not timer:
            self.timer = self.get_time = time.process_time
            self.dispatcher = self.trace_dispatch_i
        else:
            self.timer = timer
            t = self.timer() # test out timer function
            try:
                length = len(t)
            except TypeError:
                self.get_time = timer
                self.dispatcher = self.trace_dispatch_i
            else:
                if length == 2:
                    self.dispatcher = self.trace_dispatch
                else:
                    self.dispatcher = self.trace_dispatch_l
                # This get_time() implementation needs to be defined
                # here to capture the passed-in timer in the parameter
                # list (for performance).  Note that we can't assume
                # the timer() result contains two values in all
                # cases.
                def get_time_timer(timer=timer, sum=sum):
                    return sum(timer())
                self.get_time = get_time_timer
        self.t = self.get_time()
        self.simulate_call('profiler')

    # Heavily optimized dispatch routine for time.process_time() timer 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: test_time.py    GNU General Public License v3.0 5 votes vote down vote up
def test_process_time(self):
        # process_time() should not include time spend during a sleep
        start = time.process_time()
        time.sleep(0.100)
        stop = time.process_time()
        # use 20 ms because process_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        info = time.get_clock_info('process_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable) 
Example 27
Project: sympad   Author: Pristine-Cat   File: test_sym.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse (text, retprepost = False):
	t0  = time.process_time ()
	ret = parser.parse (text)
	t   = time.process_time () - t0

	if t > 2:
		print ()
		print (f'Slow parse {t}s: \n{text}', file = sys.stderr)

	if not ret [0] or ret [1] or ret [2]:
		return None

	return (ret [0], ret [0].pre_parse_postprocess) if retprepost else ret [0] 
Example 28
Project: vo_single_camera_sos   Author: ubuntuslave   File: camera_models.py    GNU General Public License v3.0 5 votes vote down vote up
def view_all_panoramas(self, omni_images_filename_pattern, img_indices, win_name_modifier = "", use_mask = False, mask_color_RGB = None):
        import warnings
        from omnistereo.common_cv import get_images

        omni_images = get_images(omni_images_filename_pattern, indices_list = img_indices, show_images = not use_mask)

        if img_indices is None or len(img_indices) == 0:  # Default value
            # use all the images in the set:
            img_indices = range(len(omni_images))

        for i in img_indices:
            try:
                #===============================================================
                # from time import process_time  # , perf_counter
                # start_time = process_time()
                #===============================================================
                pano_img_top, pano_img_bot = self.generate_panorama_pair(omni_images[i], idx = i, view = True, win_name_modifier = win_name_modifier, use_mask = use_mask, border_RGB_color = mask_color_RGB)
                #===============================================================
                # end_time = process_time()
                # time_ellapsed_1 = end_time - start_time
                # print("Time elapsed: {time:.8f} seconds".format(time=time_ellapsed_1))
                #===============================================================
                save_panos_to_file = False
                if save_panos_to_file:
                    num_of_zero_padding = 6
                    n = str(i)
                    cv2.imwrite("/tmp/panorama-%s-%s.png" % (self.top_model.mirror_name, n.zfill(num_of_zero_padding)), pano_img_top)
                    cv2.imwrite("/tmp/panorama-%s-%s.png" % (self.bot_model.mirror_name, n.zfill(num_of_zero_padding)), pano_img_bot)

            except:
                warnings.warn("Image index %d not found at %s" % (i, __name__)) 
Example 29
Project: Blender-For-UnrealEngine-Addons   Author: xavier150   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def execute(self, context):
			scene = bpy.context.scene
			def GetIfOneTypeCheck():
				if (scene.static_export
				or scene.skeletal_export
				or scene.anin_export
				or scene.alembic_export
				or scene.camera_export):
					return True
				else:
					return False

			if GetIfOneTypeCheck():
				#Primary check	if file is saved to avoid windows PermissionError
				if bpy.data.is_saved:
					scene.UnrealExportedAssetsList.clear()
					start_time = time.process_time()
					UpdateNameHierarchy()
					bfu_ExportAsset.ExportForUnrealEngine()
					bfu_WriteText.WriteAllTextFiles()

					if len(scene.UnrealExportedAssetsList) > 0:
						self.report({'INFO'}, "Export of "+str(len(scene.UnrealExportedAssetsList))+
						" asset(s) has been finalized in "+str(time.process_time()-start_time)+" sec. Look in console for more info.")
						print("========================= Exported asset(s) =========================")
						print("")
						for line in bfu_WriteText.WriteExportLog().splitlines():
							print(line)
						print("")
						print("========================= ... =========================")
					else:
						self.report({'WARNING'}, "Not found assets. with \"Export and child\" properties.")
				else:
					self.report({'WARNING'}, "Please save this blend file before export")
			else:
				self.report({'WARNING'}, "No asset type is checked.")
			return {'FINISHED'}


	#Categories : 
Example 30
Project: Blender-For-UnrealEngine-Addons   Author: xavier150   File: bfu_ExportAsset.py    GNU General Public License v3.0 5 votes vote down vote up
def ExportSingleAlembicAnimation(dirpath, filename, obj):
	#Export a single alembic animation

	scene = bpy.context.scene
	filename = ValidFilenameForUnreal(filename)
	curr_time = time.process_time()
	if	bpy.ops.object.mode_set.poll():
		bpy.ops.object.mode_set(mode = 'OBJECT')
	originalLoc = Vector((0,0,0))
	originalLoc = originalLoc + obj.location #Save current object location
	#obj.location = (0,0,0) #Moves object to the center of the scene for export
	SelectParentAndDesiredChilds(obj)

	if obj.AddOneAdditionalFramesAtTheEnd == True:
		scene.frame_end += 1
	absdirpath = bpy.path.abspath(dirpath)
	VerifiDirs(absdirpath)
	fullpath = os.path.join( absdirpath , filename )

	##Export
	bpy.ops.wm.alembic_export(
		filepath=fullpath,
		check_existing=False,
		selected=True,
		triangulate=False,
		#global_scale = GetObjExportScale(obj) #don't work with Unreal
		)

	#obj.location = originalLoc #Resets previous object location
	if obj.AddOneAdditionalFramesAtTheEnd == True:
		scene.frame_end -= 1
	exportTime = time.process_time()-curr_time

	MyAsset = scene.UnrealExportedAssetsList.add()
	MyAsset.assetName = filename
	MyAsset.assetType = "Alembic"
	MyAsset.exportPath = absdirpath
	MyAsset.exportTime = exportTime
	MyAsset.object = obj
	return MyAsset 
Example 31
Project: Blender-For-UnrealEngine-Addons   Author: xavier150   File: bfu_WriteText.py    GNU General Public License v3.0 5 votes vote down vote up
def ExportSingleText(text, dirpath, filename):
	#Export single text

	filename = ValidFilename(filename)
	curr_time = time.process_time()

	absdirpath = bpy.path.abspath(dirpath)
	VerifiDirs(absdirpath)
	fullpath = os.path.join( absdirpath , filename )

	with open(fullpath, "w") as file:
		file.write(text)

	exportTime = time.process_time()-curr_time
	return([filename,"TextFile",absdirpath,exportTime]) #[AssetName , AssetType , ExportPath, ExportTime] 
Example 32
Project: Blender-For-UnrealEngine-Addons   Author: xavier150   File: bfu_WriteText.py    GNU General Public License v3.0 5 votes vote down vote up
def ExportSingleConfigParser(config, dirpath, filename):
	#Export single ConfigParser

	filename = ValidFilename(filename)
	curr_time = time.process_time()

	absdirpath = bpy.path.abspath(dirpath)
	VerifiDirs(absdirpath)
	fullpath = os.path.join( absdirpath , filename )

	with open(fullpath, "w") as configfile:
		config.write(configfile)

	exportTime = time.process_time()-curr_time
	return([filename,"TextFile",absdirpath,exportTime]) #[AssetName , AssetType , ExportPath, ExportTime] 
Example 33
Project: Blender-For-UnrealEngine-Addons   Author: xavier150   File: bfu_ExportAsset.py    GNU General Public License v3.0 5 votes vote down vote up
def ExportSingleAlembicAnimation(originalScene, dirpath, filename, obj):
	#Export a single alembic animation

	scene = bpy.context.scene
	filename = ValidFilenameForUnreal(filename)
	curr_time = time.process_time()
	if	bpy.ops.object.mode_set.poll():
		bpy.ops.object.mode_set(mode = 'OBJECT')

	SelectParentAndDesiredChilds(obj)

	scene.frame_start += obj.StartFramesOffset
	scene.frame_end += obj.EndFramesOffset
	absdirpath = bpy.path.abspath(dirpath)
	VerifiDirs(absdirpath)
	fullpath = os.path.join( absdirpath , filename )

	##Export
	bpy.ops.wm.alembic_export(
		filepath=fullpath,
		check_existing=False,
		selected=True,
		triangulate=False,
		)

	scene.frame_start -= obj.StartFramesOffset
	scene.frame_end -= obj.EndFramesOffset
	exportTime = time.process_time()-curr_time

	MyAsset = originalScene.UnrealExportedAssetsList.add()
	MyAsset.assetName = filename
	MyAsset.assetType = "Alembic"
	MyAsset.exportPath = absdirpath
	MyAsset.exportTime = exportTime
	MyAsset.object = obj
	return MyAsset 
Example 34
Project: Blender-For-UnrealEngine-Addons   Author: xavier150   File: bfu_WriteText.py    GNU General Public License v3.0 5 votes vote down vote up
def ExportSingleText(text, dirpath, filename):
	#Export single text

	filename = ValidFilename(filename)
	curr_time = time.process_time()

	absdirpath = bpy.path.abspath(dirpath)
	VerifiDirs(absdirpath)
	fullpath = os.path.join( absdirpath , filename )

	with open(fullpath, "w") as file:
		file.write(text)

	exportTime = time.process_time()-curr_time
	return([filename,"TextFile",absdirpath,exportTime]) #[AssetName , AssetType , ExportPath, ExportTime] 
Example 35
Project: Blender-For-UnrealEngine-Addons   Author: xavier150   File: bfu_WriteText.py    GNU General Public License v3.0 5 votes vote down vote up
def ExportSingleConfigParser(config, dirpath, filename):
	#Export single ConfigParser

	filename = ValidFilename(filename)
	curr_time = time.process_time()

	absdirpath = bpy.path.abspath(dirpath)
	VerifiDirs(absdirpath)
	fullpath = os.path.join( absdirpath , filename )

	with open(fullpath, "w") as configfile:
		config.write(configfile)

	exportTime = time.process_time()-curr_time
	return([filename,"TextFile",absdirpath,exportTime]) #[AssetName , AssetType , ExportPath, ExportTime] 
Example 36
Project: eventsourcing   Author: johnbywater   File: runner.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def do_tick(self, process_time: float, tick_time: float) -> None:
        # Todo: Pull these members up from subclasses.
        tick_duration = tick_time - self.last_tick_time
        self.all_tick_durations.append(tick_duration)
        if len(self.all_tick_durations) > self.tick_durations_window_size:
            self.all_tick_durations.popleft()
        if self.is_verbose:
            process_duration = process_time - self.last_process_time
            intensity = 100 * process_duration / tick_duration
            clock_speed = 1 / tick_duration
            real_time = self.tick_count / self.normal_speed
            print(
                f"Tick {self.tick_count:4}: {real_time:4.2f}s  "
                f"{tick_duration:.6f}s, "
                f"{intensity:6.2f}%, {clock_speed:6.1f}Hz, "
                f"{self.actual_clock_speed:6.1f}Hz, "
                f"{self.tick_adjustment:.6f}s"
            )
        if self.tick_interval:
            tick_oversize = tick_duration - self.tick_interval
            tick_oversize_percentage = 100 * (tick_oversize) / self.tick_interval
            # if tick_oversize_percentage > 300:
            #     print(f"Warning: Tick over size: { tick_duration :.6f}s
            #     {tick_oversize_percentage:.2f}%")

            if abs(tick_oversize_percentage) < 300:
                # Weight falls from 1 as reciprocal of count, to tick
                # interval.
                # weight = max(1 / self.tick_count, min(.1,
                # self.tick_interval))
                weight = 1 / (1 + self.tick_count * self.tick_interval) ** 2
                # print(f"Weight: {weight:.4f}")
                self.tick_adjustment += weight * tick_oversize
                max_tick_adjustment = 1.0 * self.tick_interval
                min_tick_adjustment = 0
                self.tick_adjustment = min(self.tick_adjustment, max_tick_adjustment)
                self.tick_adjustment = max(self.tick_adjustment, min_tick_adjustment) 
Example 37
Project: sqlmap-gtk   Author: needle-wang   File: opts_gtk.py    GNU General Public License v3.0 5 votes vote down vote up
def main():
  import time
  from widgets import d
  from model import Model
  from handlers import Handler

  start = time.process_time()
  # --------
  win = g.Window(title = 'options-gtk')

  css_provider = g.CssProvider.new()
  css_provider.load_from_path('css.css')
  g.StyleContext.add_provider_for_screen(
    d.Screen.get_default(),
    css_provider,
    g.STYLE_PROVIDER_PRIORITY_APPLICATION
  )

  m = Model()
  n = Notebook(m, Handler(win, m))
  win.add(n)

  win.connect('destroy', g.main_quit)
  win.show_all()
  # --------
  end = time.process_time()
  print('loading cost: %s Seconds' % (end - start))
  g.main() 
Example 38
Project: ImageColorTheme   Author: rainyear   File: test.py    MIT License 5 votes vote down vote up
def testMMCQ(pixDatas, maxColor):
    start  = time.process_time()
    themes = list(map(lambda d: MMCQ(d, maxColor).quantize(), pixDatas))
    print("MMCQ Time cost: {0}".format(time.process_time() - start))
    return themes
    # imgPalette(pixDatas, themes) 
Example 39
Project: ImageColorTheme   Author: rainyear   File: test.py    MIT License 5 votes vote down vote up
def testOQ(pixDatas, maxColor):
    start  = time.process_time()
    themes = list(map(lambda d: OQ(d, maxColor).quantize(), pixDatas))
    print("OQ Time cost: {0}".format(time.process_time() - start))
    return themes
    # imgPalette(pixDatas, themes) 
Example 40
Project: ImageColorTheme   Author: rainyear   File: test.py    MIT License 5 votes vote down vote up
def testKmeans(pixDatas, maxColor, skl=True):
    start = time.process_time()
    themes = list(map(lambda d: KMeans(d, maxColor, skl).quantize(), pixDatas))
    print("KMeans Time cost: {0}".format(time.process_time() - start))
    return themes 
Example 41
Project: skan   Author: jni   File: bench_skan.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def timer():
    time = []
    t0 = process_time()
    yield time
    t1 = process_time()
    time.append(t1 - t0) 
Example 42
Project: skan   Author: jni   File: test_skeleton_class.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_path_length_caching():
    skeleton = Skeleton(skeleton3d)
    t0 = process_time()
    distances = skeleton.path_lengths()
    t1 = process_time()
    distances2 = skeleton.path_lengths()
    t2 = process_time()
    assert t2 - t1 < t1 - t0
    assert np.all((distances > 0.99 + np.sqrt(2))
                  & (distances < 5.01 + 5 * np.sqrt(2))) 
Example 43
Project: Fusion360CaptiveJointAddin   Author: sirusdv   File: Fusion360DebugUtilities.py    MIT License 5 votes vote down vote up
def perf_log(log, function_reference, command, identifier=''):
    log.append((function_reference, command, identifier, time.process_time())) 
Example 44
Project: pyuavcan   Author: UAVCAN   File: _random.py    MIT License 5 votes vote down vote up
def _test_type(model: pydsdl.CompositeType, num_random_samples: int) -> _TypeTestStatistics:
    _logger.debug('Roundtrip serialization test of %s with %d random samples', model, num_random_samples)
    dtype = pyuavcan.dsdl.get_class(model)
    samples: typing.List[typing.Tuple[float, float]] = [
        _serialize_deserialize(dtype())
    ]
    rand_sr_validness: typing.List[bool] = []

    def once(obj: pyuavcan.dsdl.CompositeObject) -> typing.Tuple[float, float]:
        s = _serialize_deserialize(obj)
        samples.append(s)
        return s

    for index in range(num_random_samples):
        ts = time.process_time()
        # Forward test: get random object, serialize, deserialize, compare
        sample_ser = once(_util.make_random_object(model))

        # Reverse test: get random serialized representation, deserialize; if successful, serialize again and compare
        sr = _make_random_fragmented_serialized_representation(pyuavcan.dsdl.get_model(dtype).bit_length_set)
        ob = pyuavcan.dsdl.deserialize(dtype, sr)
        rand_sr_validness.append(ob is not None)
        sample_des: typing.Optional[typing.Tuple[float, float]] = None
        if ob:
            sample_des = once(ob)

        elapsed = time.process_time() - ts
        if elapsed > 1.0:
            duration_ser = f'{sample_ser[0] * 1e6:.0f}/{sample_ser[1] * 1e6:.0f}'
            duration_des = f'{sample_des[0] * 1e6:.0f}/{sample_des[1] * 1e6:.0f}' if sample_des else 'N/A'
            _logger.debug(f'Random sample {index + 1} of {num_random_samples} took {elapsed:.1f} s; '
                          f'random SR correct: {ob is not None}; '
                          f'duration forward/reverse [us]: ({duration_ser})/({duration_des})')

    out = numpy.mean(samples, axis=0)
    assert out.shape == (2,)
    return _TypeTestStatistics(
        mean_serialization_time=out[0],
        mean_deserialization_time=out[1],
        random_serialized_representation_correctness_ratio=float(numpy.mean(rand_sr_validness)),
    ) 
Example 45
Project: pyuavcan   Author: UAVCAN   File: _random.py    MIT License 5 votes vote down vote up
def _serialize_deserialize(obj: pyuavcan.dsdl.CompositeObject) -> typing.Tuple[float, float]:
    gc.collect()
    gc.disable()        # Must be disabled, otherwise it induces spurious false-positive performance warnings

    ts = time.process_time()
    chunks = list(pyuavcan.dsdl.serialize(obj))         # GC must be disabled while we're in the timed context
    ser_sample = time.process_time() - ts

    ts = time.process_time()
    d = pyuavcan.dsdl.deserialize(type(obj), chunks)    # GC must be disabled while we're in the timed context
    des_sample = time.process_time() - ts

    gc.enable()

    assert d is not None
    assert type(obj) is type(d)
    assert pyuavcan.dsdl.get_model(obj) == pyuavcan.dsdl.get_model(d)

    if not _util.are_close(pyuavcan.dsdl.get_model(obj), obj, d):  # pragma: no cover
        assert False, f'{obj} != {d}; sr: {bytes().join(chunks).hex()}'  # Branched for performance reasons

    # Similar floats may produce drastically different string representations, so if there is at least one float inside,
    # we skip the string representation equality check.
    if pydsdl.FloatType.__name__ not in repr(pyuavcan.dsdl.get_model(d)):
        assert str(obj) == str(d)
        assert repr(obj) == repr(d)

    return ser_sample, des_sample 
Example 46
Project: pymhlib   Author: ac-tuwien   File: scheduler.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, sol: Solution, methods: List[Method], own_settings: dict = None, consider_initial_sol=False,
                 population=None):
        """
        :param sol: template/initial solution
        :param methods: list of scheduler methods to apply
        :param own_settings: an own settings object for locally valid settings that override the global ones
        :param consider_initial_sol: if true consider sol as valid solution that should be improved upon; otherwise
            sol is considered just a possibly uninitialized of invalid solution template
        :param population: optional population object used in derived population-based metaheuristic
        """
        self.incumbent = sol
        self.incumbent_valid = consider_initial_sol
        self.incumbent_iteration = 0
        self.incumbent_time = 0.0
        self.population = population
        self.methods = methods
        self.method_stats = {method.name: MethodStatistics() for method in methods}
        self.iteration = 0
        self.time_start = time.process_time()
        self.run_time = None
        self.logger = logging.getLogger("pymhlib")
        self.iter_logger = logging.getLogger("pymhlib_iter")
        self.log_iteration_header()
        if self.incumbent_valid:
            self.log_iteration('-', float('NaN'), sol, True, True, None)
        self.own_settings = OwnSettings(own_settings) if own_settings else settings 
Example 47
Project: pymhlib   Author: ac-tuwien   File: scheduler.py    GNU General Public License v3.0 5 votes vote down vote up
def perform_method(self, method: Method, sol: Solution, delayed_success=False) -> Result:
        """Perform method on given solution and returns Results object.

        Also updates incumbent, iteration and the method's statistics in method_stats.
        Furthermore checks the termination condition and eventually sets terminate in the returned Results object.

        :param method: method to be performed
        :param sol: solution to which the method is applied
        :param delayed_success: if set the success is not immediately determined and updated but at some later
                call of delayed_success_update()
        :returns: Results object
        """
        res = Result()
        obj_old = sol.obj()
        t_start = time.process_time()
        method.func(sol, method.par, res)
        t_end = time.process_time()
        if __debug__ and self.own_settings.mh_checkit:
            sol.check()
        ms = self.method_stats[method.name]
        ms.applications += 1
        ms.netto_time += t_end - t_start
        obj_new = sol.obj()
        if not delayed_success:
            ms.brutto_time += t_end - t_start
            if sol.is_better_obj(sol.obj(), obj_old):
                ms.successes += 1
                ms.obj_gain += obj_new - obj_old
        self.iteration += 1
        new_incumbent = self.update_incumbent(sol, t_end - self.time_start)
        terminate = self.check_termination()
        self.log_iteration(method.name, obj_old, sol, new_incumbent, terminate, res.log_info)
        if terminate:
            self.run_time = time.process_time() - self.time_start
            res.terminate = True
        return res 
Example 48
Project: pymhlib   Author: ac-tuwien   File: scheduler.py    GNU General Public License v3.0 5 votes vote down vote up
def perform_methods(self, methods: List[Method], sol: Solution) -> Result:
        """Performs all methods on given solution and returns Results object.

        Also updates incumbent, iteration and the method's statistics in method_stats.
        Furthermore checks the termination condition and eventually sets terminate in the returned Results object.

        :param methods: list of methods to perform
        :param sol: solution to which the method is applied
        :returns: Results object
        """
        res = Result()
        obj_old = sol.obj()
        method_name = ""
        for method in methods:
            if method_name != "":
                method_name += "+"
            method_name += method.name

            method.func(sol, method.par, res)
            if res.terminate:
                break
        t_end = time.process_time()

        self.iteration += 1
        new_incumbent = self.update_incumbent(sol, t_end - self.time_start)
        terminate = self.check_termination()
        self.log_iteration(method_name, obj_old, sol, new_incumbent, terminate, res.log_info)
        if terminate:
            self.run_time = time.process_time() - self.time_start
            res.terminate = True

        return res 
Example 49
Project: pymhlib   Author: ac-tuwien   File: scheduler.py    GNU General Public License v3.0 5 votes vote down vote up
def delayed_success_update(self, method: Method, obj_old: TObj, t_start: float, sol: Solution):
        """Update an earlier performed method's success information in method_stats.

        :param method: earlier performed method
        :param obj_old: objective value of solution with which to compare to determine success
        :param t_start: time when the application of method had started
        :param sol: current solution considered the final result of the method
        """
        t_end = time.process_time()
        ms = self.method_stats[method.name]
        ms.brutto_time += t_end - t_start
        obj_new = sol.obj()
        if sol.is_better_obj(sol.obj(), obj_old):
            ms.successes += 1
            ms.obj_gain += obj_new - obj_old 
Example 50
Project: pymhlib   Author: ac-tuwien   File: scheduler.py    GNU General Public License v3.0 5 votes vote down vote up
def check_termination(self) -> bool:
        """Check termination conditions and return True when to terminate."""
        t = time.process_time()
        if 0 <= self.own_settings.mh_titer <= self.iteration or \
                0 <= self.own_settings.mh_tciter <= self.iteration - self.incumbent_iteration or \
                0 <= self.own_settings.mh_ttime <= t - self.time_start or \
                0 <= self.own_settings.mh_tctime <= t - self.incumbent_time or \
                0 <= self.own_settings.mh_tobj and not self.incumbent.is_worse_obj(self.incumbent.obj(),
                                                                                   self.own_settings.mh_tobj):
            return True
        return False