为了对我的应用程序进行负载测试(在 Linux 下),我正在寻找一种能够以特定速率(例如 100 字节/秒)在 stdout 上输出数据的工具,以便我可以将输出通过管道传输到 netcat,后者发送它到我的应用程序。 dd 的一些选项是理想的,但到目前为止我没有找到任何东西。打印什么样的数据并不重要(NUL 字节也可以)。有什么提示吗?
最佳答案
我写了一个快速程序,它接受一个参数,即每秒打印到标准输出的 A
字符数(负参数表示没有速率限制)。希望这可以帮助! :-)(在 GNU libc 上,您需要将您的程序与 -lrt
链接。)
编辑:修改为默认打印点,除非指定第二个参数,在这种情况下使用第一个字符。 (这意味着,如果你想打印 NUL 字符,只需指定一个空字符串作为第二个参数。:-))
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
int
sleeptill(const struct timespec *when)
{
struct timespec now, diff;
clock_gettime(CLOCK_REALTIME, &now);
diff.tv_sec = when->tv_sec - now.tv_sec;
diff.tv_nsec = when->tv_nsec - now.tv_nsec;
while (diff.tv_nsec < 0) {
diff.tv_nsec += 1000000000;
--diff.tv_sec;
}
if (diff.tv_sec < 0)
return 0;
return nanosleep(&diff, 0);
}
int
main(int argc, char **argv)
{
double rate = 0.0;
char *endp;
struct timespec start;
double offset;
if (argc >= 2) {
rate = strtod(argv[1], &endp);
if (endp == argv[1] || *endp)
rate = 0.0;
else
rate = 1 / rate;
if (!argv[2])
argv[2] = ".";
}
if (!rate) {
fprintf(stderr, "usage: %s rate [char]\n", argv[0]);
return 1;
}
clock_gettime(CLOCK_REALTIME, &start);
offset = start.tv_nsec / 1000000000.0;
while (1) {
struct timespec till = start;
double frac;
double whole;
frac = modf(offset += rate, &whole);
till.tv_sec += whole;
till.tv_nsec = frac * 1000000000.0;
sleeptill(&till);
write(STDOUT_FILENO, argv[2], 1);
}
}
关于linux - 以特定速度执行 stdout 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/242697/