linux - 以特定速度执行 stdout 输出

标签 linux performance limit dd

为了对我的应用程序进行负载测试(在 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/

相关文章:

linux - 自动登录网站并下载文件的脚本

linux - 数据包在内核中的旅程如何?

linux - Bash - 硬件信息(脚本中的西类牙语文本)

database - 数据库设计 : efficiency consideration when adding an intermediate class into a Many-Many relationship

java - 加载 100 条记录 10 x 10 jtable java 的文本文件?

c - 如何限制用户在C中输入一位小数点的 float

c - C 中的 IPPROTO_TCP IP_TOS 的 setsockopt 失败

c++ - 我应该避免循环中常量之间的操作吗?

sql - 加快数据在两个日期之间的 PostgreSQL 查询

php - 参数化 PDO 查询和 `LIMIT` 子句 - 不工作