5

我正在为 Go 中的 SQRL 客户端实现 EnScrypt。该函数需要运行,直到它使用了最少的 CPU 时间。我的 Python 代码如下所示:

def enscrypt_time(salt, password, seconds, n=9, r=256):
    N = 1 << n
    start = time.process_time()
    end = start + seconds
    data = acc = scrypt.hash(password, salt, N, r, 1, 32)
    i = 1
    while time.process_time() < end:
        data = scrypt.hash(password, data, N, r, 1, 32)
        acc = xor_bytes(acc, data)
        i += 1
    return i, time.process_time() - start, acc

process_time除了函数之外,将其转换为 Go 非常简单。我不能使用time.Time/Timer因为它们测量挂钟时间(受系统上可能运行的所有其他内容的影响)。我需要实际使用的 CPU 时间,理想情况下是函数,或者至少是它运行的线程或进程。

Go 相当于process_time什么?

https://docs.python.org/3/library/time.html#time.process_time

4

1 回答 1

3

您可以使用runtime.LockOSThread()将调用 goroutine 连接到其当前 OS 线程。这将确保不会将其他 goroutine 安排到该线程,因此您的 goroutine 将运行并且不会被中断或暂停。当线程被锁定时,没有其他 goroutine 会干扰。

在此之后,您只需要一个循环,直到给定的秒数过去。您必须调用runtime.UnlockOSThread()以“释放”线程并使其可用于其他 goroutine 执行,最好作为defer语句完成。

看这个例子:

func runUntil(end time.Time) {
    runtime.LockOSThread()
    defer runtime.UnlockOSThread()
    for time.Now().Before(end) {
    }
}

让它等待 2 秒,它可能看起来像这样:

start := time.Now()
end := start.Add(time.Second * 2)
runUntil(end)

fmt.Println("Verify:", time.Now().Sub(start))

例如,这打印:

Verify: 2.0004556s

当然,您也可以指定不到一秒,例如等待 100 毫秒:

start := time.Now()
runUntil(start.Add(time.Millisecond * 100))
fmt.Println("Verify:", time.Now().Sub(start))

输出:

Verify: 100.1278ms

如果更适合您,您可以使用此函数的不同版本,它需要花费时间“等待”作为值time.Duration

func wait(d time.Duration) {
    runtime.LockOSThread()
    defer runtime.UnlockOSThread()

    for end := time.Now().Add(d); time.Now().Before(end); {
    }
}

使用这个:

start = time.Now()
wait(time.Millisecond * 200)
fmt.Println("Verify:", time.Now().Sub(start))

输出:

Verify: 200.1546ms

注意:请注意,上述函数中的循环将无情地使用 CPU,因为其中没有睡眠或阻塞 IO,它们只会查询当前系统时间并将其与截止日期进行比较。

如果攻击者通过多次并发尝试增加系统负载怎么办?

Go 运行时限制了可以同时执行 goroutine 的系统线程。这是由 控制的runtime.GOMAXPROCS(),所以这已经是一个限制。它默认为可用 CPU 内核的数量,您可以随时更改它。但是,这也造成了瓶颈,因为使用runtime.LockOSThread(),如果在任何给定时间锁定的线程数等于GOMAXPROCS,这将阻止其他 goroutine 的执行,直到线程被解锁。

查看相关问题:

Go 运行时使用的线程数

为什么在golang写文件时阻塞了很多goroutine,却没有创建很多线程?

于 2016-10-16T04:54:42.207 回答