以下是一个简单的基于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)来发送请求,并可能需要添加其他功能,如设置请求超时、处理重定向等。此外,请确保您有合法的权限和授权来对目标网站进行压力测试。