用c语言写个网站压力测试系统

以下是一个简单的基于C语言的网站压力测试系统示例,该系统使用多线程并发请求来模拟用户访问网站的压力:

#include <stdio.h>  
#include <stdlib.h>  
#include <pthread.h>  
#include <time.h>  
  
#define NUM_THREADS 100 // 线程数量  
#define URL "http://example.com" // 目标网站URL  
  
void *test_load(void *threadid) {  
    long tid = (long)threadid;  
    printf("Thread %ld started\n", tid);  
      
    // 发送HTTP请求  
    // 这里可以使用libcurl库或其他HTTP客户端库来发送请求  
    // 示例使用系统调用get请求目标URL  
    FILE *fp;  
    char request[100];  
    sprintf(request, "GET / HTTP/1.1\r\nHost: %s\r\n\r\n", URL);  
    fp = popen("curl -s -d @-", "w");  
    fwrite(request, sizeof(char), strlen(request), fp);  
    fclose(fp);  
      
    printf("Thread %ld finished\n", tid);  
    pthread_exit(NULL);  
}  
  
int main() {  
    pthread_t threads[NUM_THREADS];  
    int rc;  
    long t;  
    clock_t start, end;  
    double cpu_time_used;  
      
    // 记录测试开始时间  
    start = clock();  
    printf("Stress test started at %s", asctime(localtime(start)));  
      
    // 创建线程并发执行压力测试  
    for(t = 0; t < NUM_THREADS; t++) {  
        rc = pthread_create(&threads[t], NULL, test_load, (void *)t);  
        if (rc) {  
            printf("Error: return code from pthread_create() is %d\n", rc);  
            exit(-1);  
        }  
    }  
      
    // 等待所有线程完成  
    for(t = 0; t < NUM_THREADS; t++) {  
        pthread_join(threads[t], NULL);  
    }  
      
    // 记录测试结束时间并计算CPU时间消耗  
    end = clock();  
    cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;  
    printf("Stress test finished at %s", asctime(localtime(end)));  
    printf("Test duration: %.2f seconds\n", cpu_time_used);  
    printf("Test result: %ld threads executed successfully\n", NUM_THREADS);  
    return 0;  
}

请注意,这只是一个简单的示例,用于演示如何使用多线程并发发送HTTP请求。在实际应用中,您可能需要使用更高级的HTTP客户端库(如libcurl)来发送请求,并可能需要添加其他功能,如设置请求超时、处理重定向等。此外,请确保您有合法的权限和授权来对目标网站进行压力测试。

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值