Diff of /HomoAug/utils/misc.py [000000] .. [b40915]

Switch to unified view

a b/HomoAug/utils/misc.py
1
import hashlib
2
import os
3
import signal
4
import subprocess
5
import sys
6
import time
7
8
9
def time2str(time_used):
10
    gaps = [
11
        ('days', 86400000),
12
        ('h', 3600000),
13
        ('min', 60000),
14
        ('s', 1000),
15
        ('ms', 1)
16
    ]
17
    time_used *= 1000
18
    time_str = []
19
    for unit, gap in gaps:
20
        val = time_used // gap
21
        if val > 0:
22
            time_str.append('{}{}'.format(int(val), unit))
23
            time_used -= val * gap
24
    if len(time_str) == 0:
25
        time_str.append('0ms')
26
    return ' '.join(time_str)
27
28
29
def get_date():
30
    return time.strftime('%Y-%m-%d', time.localtime(time.time()))
31
32
def get_time(t=None):
33
    if t is None:
34
        t = time.time()
35
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))
36
37
38
def hash_seed(*items, width=32):
39
    # width: range of seed: [0, 2**width)
40
    sha = hashlib.sha256()
41
    for item in items:
42
        sha.update(str(item).encode('utf-8'))
43
    return int(sha.hexdigest()[23:23+width//4], 16)
44
45
46
def execute(command, verbose=False, cmd_out_off=False):
47
    if verbose:
48
        print(command)
49
        print()
50
    if cmd_out_off:
51
        popen = silent(subprocess.Popen)
52
    else:
53
        popen = subprocess.Popen
54
    p = popen(command, shell=True)
55
    try:
56
        p.wait()
57
    except KeyboardInterrupt:
58
        try:
59
            os.kill(p.pid, signal.SIGINT)
60
        except OSError:
61
            pass
62
        p.wait()
63
64
65
def silent(func):
66
    """
67
    Make function silent.
68
    Useful for closing the output if you don't find a switch.
69
    """
70
    def wrap_silent(*args, **kwargs):
71
        fd = os.dup(1)
72
        sys.stdout.flush()
73
        os.close(1)
74
        os.open(os.devnull, os.O_WRONLY)
75
76
        res = func(*args, **kwargs)
77
78
        os.close(1)
79
        os.dup(fd)
80
        os.close(fd)
81
82
        return res
83
    return wrap_silent
84
85
86
def with_time(func, pretty_time=False):
87
    """
88
    Usage:
89
90
    1. as a function decorator
91
    ``` python
92
    @with_time
93
    def func(...):
94
        ...
95
    result, cost_in_seconds = func(...)
96
    ```
97
98
    2. directly apply
99
    ``` python
100
    result, cost_in_seconds = with_time(func)(...)
101
    ```
102
    """
103
    def wrap_time(*args, **kwargs):
104
        start = time.time()
105
        res = func(*args, **kwargs)
106
        time_cost = time.time() - start
107
        if pretty_time:
108
            time_cost = time2str(time_cost)
109
        return res, time_cost
110
    return wrap_time
111